简体   繁体   English

用于更改空白选项标签文本的 Javascript

[英]Javascript to change text of a blank option tag

I am fairly new to javascript and have tried to work this out on my own, but I am new to some the objects and properties.我对javascript相当陌生,并试图自己解决这个问题,但我对某些对象和属性不熟悉。 I believe that the code I have below would work for changing "all" "option" text in the document, but I need it to only change the text value of empty option tags eg;我相信我下面的代码可以用于更改文档中的“所有”“选项”文本,但我只需要它来更改空选项标签的文本值,例如; <option></option> , to <option>Choose One</option> . <option></option> ,到<option>Choose One</option> I would like it to do this on page load, as the page is generated dynamically by asp.我希望它在页面加载时执行此操作,因为页面是由 asp 动态生成的。

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

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';

"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.您的语法无效,所以我不确定为什么您认为它会更改所有option元素。

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";

If you really want to change all <option> s without content, you can use this code如果你真的想改变所有没有内容的<option> ,你可以使用这个代码

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

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

Assuming that the empty <option> s will always be the first within each <select> tag, change to假设空的<option>将始终是每个<select>标签中的第一个,更改为

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

to save some computations.以节省一些计算。

EDIT编辑

querySelectorAll() is supported on all modern browsers, but not in IE7 and previous versions!所有现代浏览器都支持querySelectorAll() ,但不支持 IE7 和以前的版本! See caniuse.com .参见caniuse.com

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

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