我试图在jQuery的下拉列表中使用append时添加多个attr()值。

这工作正常:

$('#twostages').append($('<option/>').attr("value", option.stage).text(option.stage));


我可以使用以下方法访问值:

document.getElementById("twostages").value


但是,当我尝试以下代码时:

$('#twostages').append($('<option/>').attr({ "value": option.stage, "matone": option.matone }).text(option.stage));


我无法使用valuematone检索document.getElementById("twostages").valuedocument.getElementById("twostages").matone

我从这个主题得到了上面代码的想法:jQuery: Adding two attributes via the .attr(); method

任何帮助将不胜感激。

谢谢。

最佳答案

matone是在选项上添加的属性。因此,您不能直接访问它。

您需要先检查选定的选项,然后使用matone获取它的相应.attr()

工作片段:-



$('#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>





参考:-

.attr()

:selected

注意:-通常的做法是对自定义属性使用data-attributes

关于javascript - 在下拉列表中使用添加时添加多个属性-jQuery,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53149657/

10-12 12:57
查看更多