简体   繁体   English

如何在不使用jQuery的情况下设置选择选项值?

[英]How can I set a select option value without using jQuery?

I am trying to convert a jQuery code into pure Javascript 我正在尝试将jQuery代码转换为纯Javascript

$('.city option[value="NY"]').attr('selected','selected');

How can I do it? 我该怎么做? I am trying the following code but it gives me an error 我正在尝试以下代码,但它给我一个错误

document.getElementsByClassName('.city option[value="NY"]')
    .setAttribute('selected','selected');

Error: 错误:

 document.getElementsByClassName(...).setAttribute is not a function

html: HTML:

 <select name="city" id="city" class="form-control">
    <option value="77">29 Palms</option>
    <option value="183">Acton</option>
    <option value="270">Adelanto</option>
    <option value="348">Agoura Hills</option>
    <option value="353">Agua Dulce</option>
    <option value="360">Aguanga</option>
    <option value="372">Ahwahnee</option>
    <option value="622">Alhambra</option></select>

Note: IE8+ only 注意:仅限IE8 +

Use querySelector as you are trying to find an element with a class and attribute selectors 在尝试查找具有类和属性选择器的元素时使用querySelector

var els = document.querySelector('.city option[value="NY"]');
if(els){
    els.setAttribute('selected','selected');
    //or els.selected = true;
}

getElementsByClassName() takes a class name as the argument, not a complex selector like the one you have used, also it returns an array of dom elements, so you need to iterate through the array contents and then set its property getElementsByClassName()以类名作为参数,而不是像您使用的那样的复杂选择器,它还会返回一个dom元素数组,因此您需要遍历数组内容,然后设置其属性


var els = document.querySelector('select[name="city"] option[value="360"]');
if(els){
    els.selected = true;
}

Demo: Fiddle 演示: 小提琴

What about this? 那这个呢?

var cities = document.getElementsByClassName("city");
for (var i = 0; i < cities.length; i++){
    var options = this.getElementsByTagName("option");
    for (var i2 = 0; i < options.length; i2++){
        if (this.value == "NY"){
            this.setAttribute("selected", "selected")      
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM