1

我对javascript相当陌生,并试图自己解决这个问题,但我对一些对象和属性还是陌生的。我相信我下面的代码可以用于更改文档中的“所有”“选项”文本,但我需要它来仅更改空选项标签的文本值,例如;<option></option>, 到<option>Choose One</option>. 我希望它在页面加载时执行此操作,因为页面是由 asp 动态生成的。

 <script type="text/javascript">
    function changeEmpty(){
      document.getElementByTagName('option')options[0].text='Choose One';
    }
    </script>
4

3 回答 3

2

If it is going to be the first option on the page for one select it would be

document.getElementsByTagName('option')[0].text='Choose One';

It would be better to specify the element so if someone in the future adds a select before it, it will not matter.

document.getElementById("MyId").getElementsByTagName('option')[0].text='Choose One';
于 2012-11-13T16:27:58.217 回答
0

"I need it to only change the text value of empty option tags..."

Your syntax is invalid, so I'm not sure why you think it would change all option elements.

But what you can do is simply iterate them, and test the text content.

var opts = document.getElementsByTagName('option');

for (var i = 0, len = opts.length; i < len; i++) 
    if (opts[i].text === "")
        opts[i].text = "Choose One";
于 2012-11-13T16:29:40.833 回答
0

如果你真的想改变所有<option>没有内容的s,你可以使用这个代码

function changeEmpty(){
  var els = document.querySelectorAll( 'option' );

  for ( var i=els.length; i--; ) {
    if ( els.innerHTML.trim() == '' ) {
      els.innerHTML = 'choose one';
    }
  }
}

假设空<option>的 s 将始终是每个<select>标签中的第一个,更改为

var els = document.querySelectorAll( 'select > option' );

以节省一些计算。

编辑

querySelectorAll()所有现代浏览器都支持,但在 IE7 和以前的版本中不支持!请参阅caniuse.com

于 2012-11-13T16:31:13.170 回答