简体   繁体   English

多个值<option>

[英]Multiple values of <option>

I would like to put multiple values in tag within select, so I could adress precisely one or few items.我想在 select 中的 tag 中放置多个值,这样我就可以精确地处理一个或几个项目。

Example:例子:

<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>

In my js I got that one function that depend on one value that is common for many items:在我的 js 中,我得到了一个函数,该函数依赖于许多项目常见的一个值:

if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}

But I don't want to use (cos' and with more options gonna get messy)但我不想使用(因为有更多选项会变得混乱)

var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}

Neverthelesst I need to be able to set item by precise one value尽管如此,我需要能够通过精确的一个值来设置项目

if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}

Is there a nice way to achieve this?有没有一个很好的方法来实现这一目标? Maybe use some other "value-like" attribute of option (but which?)?也许使用选项的其他一些“类似价值”的属性(但哪个?)? Only JS.只有JS。

I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:我认为你可以用selectedOpt.value.split(",").includes("sth")代码做你想做的事:

 $(document).ready(function(e){ selectedChange($("#select1")[0]) }); function selectedChange(val) { var selectedOpt = val.options[val.selectedIndex]; var status1 = selectedOpt.value.split(",").includes("x2"); var status2 = selectedOpt.value.split(",").includes("pf"); console.log(status1); console.log(status2); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="select1" onchange="selectedChange(this)"> <option value="pf,nn">NN</option> <option value="pf,x2,jj">JJ</option> <option value="pf,uu">UU</option> <option value="pf,x2,oo">OO</option> <option value="tt">TT</option> <option value="rr">RR</option> </select>

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

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