Javascript更改函数触发标记名

时间:2016-10-13 11:03:04

标签: javascript jquery

我有HTML和Javascript代码,但只有一个select代码。问题是我需要它来涵盖HTML中的所有select标记。因此,选择它们时,应根据value更改所有选项中的颜色。

Some text <select> <option value='red'>wrong option</option> <option value='green'>right option</option> <option value='red'>wrong option</option> </select> some text.<br>
Some text <select> <option value='green'>right option</option> <option value='red'>wrong option</option> <option value='red'>wrong option</option> </select> some text.<br>
Some text <select> <option value='red'>wrong option</option> <option value='red'>wrong option</option> <option value='green'>right option</option> </select> some text.

仅适用于select数组中的第一个元素。

var select = document.getElementsByTagName('select');

select[0].onchange = function() {
    for(var i = 0; i < select[0].options.length; i++) {
        if(i == select[0].selectedIndex) {
            select[0].style.color = this.value;
        } else {
            select[0].options[i].style.color = 'black';
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您使用select专门定位第一个select[0]元素。如果你想将它应用于所有,你需要一个循环:

for (var i = 0; i < select.length; i++) {
  select[i].onchange = function() { ... }
}

答案 1 :(得分:0)

首先,您必须循环select并为所有选择分配监听器。

其次,您应该使用this.style.color = this.value;代替select[0].style.color = this.value;

示例

&#13;
&#13;
var select = document.getElementsByTagName('select');
  
function handleChange() {
  for (var i = 0; i < this.options.length; i++) {
    if (i == this.selectedIndex) {
      this.style.color = this.value;

    } else {
      this.options[i]
        .style.color = 'black';
    }
  }
}

for(var i = 0; i< select.length; i++)
  select[i].addEventListener('change', handleChange)
&#13;
Some text
<select>
  <option value='red'>wrong option</option>
  <option value='green'>right option</option>
  <option value='red'>wrong option</option>
</select>some text.
<br>Some text
<select>
  <option value='green'>right option</option>
  <option value='red'>wrong option</option>
  <option value='red'>wrong option</option>
</select>some text.
<br>Some text
<select>
  <option value='red'>wrong option</option>
  <option value='red'>wrong option</option>
  <option value='green'>right option</option>
</select>some text.
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用Array.forEach

var select = document.getElementsByTagName('select');

Array.prototype.forEach.call(select, function (selectElement) {
    selectElement.onchange = function () {
        for (var i = 0; i < select[0].options.length; i++) {
            if (i == select[0].selectedIndex) {
                selectElement.style.color = this.value;

            } else {
                selectElement.options[i]
                        .style.color = 'black';
            }
        }
    }
})