【问题标题】:Color change using onclick.getElementById().style.color only works in Firefox?使用 onclick.getElementById().style.color 更改颜色仅适用于 Firefox?
【发布时间】:2013-10-20 11:20:48
【问题描述】:

我有一个表格,我想使用以下代码更改第 TH 行的文本颜色:

<select>
  <option onclick="document.getElementById('tablehead').style.color=''">Default</option>
  <option onclick="document.getElementById('tablehead').style.color='red'">Red</option>
  <option onclick="document.getElementById('tablehead').style.color='yellow'">Yellow</option>
  <option onclick="document.getElementById('tablehead').style.color='green'">Green</option>
</select>

这在 Firefox 中应该可以完美运行,但是当我在任何其他浏览器中测试它时,它就无法正常工作。我在这里想念什么?

【问题讨论】:

    标签: jquery select colors html-table onclick


    【解决方案1】:

    如果你使用 jQuery,你可以监听 change 事件:

    $('select').on('change', function() {
       $('#tablehead').css('color', this.value.toLowerCase());
    });
    

    【讨论】:

      【解决方案2】:

      使用原生 javascript

      <select onchange="document.getElementById('tablehead').style.color=this.value">
        <option value=''>Default</option>
        <option value='red'>Red</option>
        <option value='yellow'>Yellow</option>
        <option value='green'>Green</option>
      </select>
      <div id="tablehead">tablehead</div>
      

      演示:Fiddle

      【讨论】:

      • 虽然你们都发布了深入而好的答案,但由于我是 js/jQuery 新手,所以我选择了这个,这对我来说最有意义 :) 无论如何,它现在可以工作了!谢谢大家!
      【解决方案3】:

      您应该观看selectonChange 事件,这需要将value 添加到您的options。您不能依赖用户通过单击选项来选择值,并且如您所见,并非所有浏览器都会触发单击事件。

      伪代码:

      <select onChange="if (this.options[this.selectedIndex].value == 1) { red } else if (this.options[this.selectedIndex].value == 2) { green }">
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 1970-01-01
        相关资源
        最近更新 更多