Javascript 使用该值选择选择框的一个选项

Javascript 使用该值选择选择框的一个选项,javascript,jquery,Javascript,Jquery,我有一个下拉框,我想根据值选择选项。不知怎的,我已经掌握了价值观,比如说3。现在我想手动选择值为3的选项 我试过这样的东西 selectBoxElement.options[selectedValues].selected = true; 其中selectedValue=3,但它不起作用。如果根据标记使用jquery,您可以执行以下操作: $(document).ready(function() { $("#yourSelectId option[value='3']").attr("se

我有一个下拉框,我想根据值选择选项。不知怎的,我已经掌握了价值观,比如说3。现在我想手动选择值为3的选项

我试过这样的东西

selectBoxElement.options[selectedValues].selected = true;

其中selectedValue=3,但它不起作用。

如果根据标记使用jquery,您可以执行以下操作:

$(document).ready(function() { $("#yourSelectId option[value='3']").attr("selected", "selected"); });
假设$未被覆盖,并且是jQuery的别名,类似的方法应该可以工作:

或者更确切地说:

$(selectBoxElement).val(selectedValue);

这更简单,并且获得了类似的结果:

如果除了jQuery标记之外,您使用的是纯JS,那么您没有明确表示您想要纯JS还是jQuery,这应该满足您的需要:

for (i=0; i<selectBoxElement.options.length; i++) {
    if (selectBoxElement.options[i].value == selectedValues) {
      selectBoxElement.options[i].selected=true;
      break;
    }
}

这很简单,请尝试以下方法

在选择框中使用选项标记的索引位置时 SelectBoxeElement.selectedIndex=index;//其中索引从0开始

当使用该值时 选择boxelement.value=value;//其中,值是在选项标记中定义的属性

希望这能解决您的问题。

可能重复的
for (i=0; i<selectBoxElement.options.length; i++) {
    if (selectBoxElement.options[i].value == selectedValues) {
      selectBoxElement.options[i].selected=true;
      break;
    }
}