JavaScript:在 new Option() 之后添加额外的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5499019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:28:28  来源:igfitidea点击:

JavaScript: add extra attribute after new Option()

javascriptattributesoption

提问by Léon

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.

我需要的是为包含特定值的新选项添加​​一个额外的属性。在这种情况下,该属性将被称为“折扣”并且该值将是一个整数。稍后我将读取属性值并根据 Option 字段中的值处理它们。

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.

现在我如何在不使用 JS 框架的情况下做到这一点。这只是我需要的一小部分代码,因此框架对于这个项目来说是多余的。

Cheers! :-)

干杯! :-)

回答by sushil bharwani

you can do something like

你可以做类似的事情


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

回答by Cory Mawhorter

I know this is old but I came across this question when I forgot it's addand not pushtoday.

我知道这是旧的,但是当我忘记它add而不是push今天时,我遇到了这个问题。

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

正确的方法是使用select.options.add.

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

回答by Niet the Dark Absol

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.

请注意,这仅在您只添加一个属性时才有效,否则您将需要一个临时变量。