jQuery从选定的下拉列表中获取html id
由于我的表单中有多个下拉列表,因此我想从其中一个选定的下拉列表中检索HTML ID。 我有关于更改的下拉列表的以下代码:
$("select[name$='product_type']").change(function(){}
使用console.log($(this).select());
我可以在控制台中看到所选的下拉ID;
将此id检索到var中的语法是什么?
只需使用$(this).attr("id")
来获取id。
您也可以使用this.id
(已在评论中提到)。 我刚刚发现$(this).attr("id")
与this.id
的性能测试 , this.id
的结果更快,这是预期的,因为它是纯javascript而不是像jQuery这样的javascript库。
你只需要id
属性:
$("select[name$='product_type']").change(function() { console.log(this.id); });
$("select[name$='product_type'] option:selected").attr("id");
在变更回调中。