JavaScript: add extra attribute after new Option()

我怕爱的太早我们不能终老 提交于 2019-12-03 07:50:08

问题


I have a piece of code that dynamically adds options to a select field depending on some other criteria. It looks somewhat like this:

if (chosen == "a_value") {
  selbox.options[selbox.options.length] = new Option('text_1','value_1');
  selbox.options[selbox.options.length] = new Option('text_2','value_2');
  selbox.options[selbox.options.length] = new Option('text_3','value_3');
}

What I need is to add an extra attribute to that new option that contains a specific value. In this case the attribute will be called "discount" and the value will be an integer. Later on I'll read the attribute values and process them based on the value in the Option field.

So an option will look like this, once the script is ready;

<option value="value_1" discount="integer">text_1</option>

Makes sense?

Now how can I do this without the use of JS frameworks. It's just this small part of code that I need, so a framework would be overkill for this project.

Cheers! :-)


回答1:


you can do something like


var o1 = new Option("key","value");
selbox.options[selbox.options.length] = o1;
o1.setAttribute("key","value");




回答2:


I know this is old but I came across this question when I forgot it's add and not push today.

The correct way is to use select.options.add.

 var opt = document.createElement('option');
 opt.value = 'hello';
 opt.text = 'world';
 opt.setAttribute('data-discount', 'integer');
 selbox.options.add(opt);



回答3:


You can combine this into one line of code:

(selbox.options[selbox.options.length] = new Option("key","value")).setAttribute("key","value");

Note that this will only work if you have just one attribute to add, otherwise you will need a temporary variable.



来源:https://stackoverflow.com/questions/5499019/javascript-add-extra-attribute-after-new-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!