[英]Adding more than one attribute when using append in dropdown - jQuery
I am trying to add more than one attr() value when using append in a dropdown in jQuery.在 jQuery 的下拉列表中使用 append 时,我试图添加多个 attr() 值。
This is working fine:这工作正常:
$('#twostages').append($('<option/>').attr("value", option.stage).text(option.stage));
And I can access the value using:我可以使用以下方法访问该值:
document.getElementById("twostages").value
However, when I try this code:但是,当我尝试此代码时:
$('#twostages').append($('<option/>').attr({ "value": option.stage, "matone": option.matone }).text(option.stage));
I am not able to retrieve the value
or matone
using the document.getElementById("twostages").value
or document.getElementById("twostages").matone
我不能检索
value
或matone
使用document.getElementById("twostages").value
或document.getElementById("twostages").matone
I got the idea of the above code from this topic: jQuery: Adding two attributes via the .attr();我从这个主题中得到了上述代码的想法: jQuery:通过 .attr() 添加两个属性; method
方法
Any help would be greatly appreciated.任何帮助将不胜感激。
Thanks.谢谢。
matone
is a property added on options.So you can't access it directly. matone
是选项上添加的属性。因此您无法直接访问它。
you need to check first the selected option and then get it's corresponding matone
value using .attr()
您需要首先检查选定的选项,然后使用
.attr()
获取其对应的matone
值
Working snippet:-工作片段:-
$('#twostages').append($('<option/>').attr({ "value":"stage1", "matone": "mymetion" }).text("stage1")); console.log($('#twostages').val()); console.log($('#twostages').find(':selected').attr('matone'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="twostages"> </select>
Reference:-参考:-
Note:- Standered practice is to use data-attributes for custom attributes注意:-标准做法是将数据属性用于自定义属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.