jQuery - 从所选选项中获取自定义属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2230704/
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-26 13:04:20  来源:igfitidea点击:

jQuery - getting custom attribute from selected option

jquery

提问by Jason

Given the following:

鉴于以下情况:

<select id="location">
    <option value="a" myTag="123">My option</option>
    <option value="b" myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
            var element = $(this);
            var myTag = element.attr("myTag");

            $('#setMyTag').val(myTag);
        });
    });
</script>

That does not work...
What do I need to do to get the value of the hidden field updated to the value of myTag when the select is changed. I'm assuming I need to do something about getting the currently selected value...?

这不起作用......
我需要做什么才能在选择更改时将隐藏字段的值更新为 myTag 的值。我假设我需要做一些事情来获取当前选定的值......?

回答by SLaks

You're adding the event handler to the <select>element.
Therefore, $(this)will be the dropdown itself, not the selected <option>.

您正在向<select>元素添加事件处理程序。
因此,$(this)将是下拉菜单本身,而不是选定的<option>.

You need to find the selected <option>, like this:

您需要找到 selected <option>,如下所示:

var option = $('option:selected', this).attr('mytag');

回答by tvanfosson

Try this:

尝试这个:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 

回答by NawaMan

That because the element is the "Select" and not "Option" in which you have the custom tag.

那是因为元素是“选择”而不是“选项”,您在其中拥有自定义标记。

Try this: $("#location option:selected").attr("myTag").

试试这个:$("#location option:selected").attr("myTag")

Hope this helps.

希望这可以帮助。

回答by Davide Gualano

Try this:

尝试这个:

$("#location").change(function(){
            var element = $("option:selected", this);
            var myTag = element.attr("myTag");

            $('#setMyTag').val(myTag);
        });

In the callback function for change(), thisrefers to the select, not to the selected option.

在 的回调函数中change()this指的是选择,而不是被选中的选项。

回答by paulo

Suppose you have many selects. This can do it:

假设你有很多选择。这可以做到:

$('.selectClass').change(function(){
    var optionSelected = $(this).find('option:selected').attr('optionAtribute');
    alert(optionSelected);//this will show the value of the atribute of that option.
});

回答by Cerin

You're pretty close:

你很接近:

var myTag = $(':selected', element).attr("myTag");

回答by openwonk

Simpler syntax if one form.

如果是一种形式,则语法更简单。

var option = $('option:selected').attr('mytag')

var option = $('option:selected').attr('mytag')

... if more than one form.

...如果不止一种形式。

var option = $('select#myform option:selected').attr('mytag')

var option = $('select#myform option:selected').attr('mytag')

回答by Curtis Fisher

Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger

这是带有 AJAX 调用的整个脚本,用于在具有多个列表的页面中定位单个列表。即使我的属性名称是“ItemKey”,在我使用“id”属性之前,上面的其他东西都不适合我。通过使用调试器

Chrome Debug

铬调试

I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.

我能够看到所选选项具有属性:带有到 JQuery“id”和值的映射。

<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>

<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');

//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){

//clear the current content of the select
$select.html('');

//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},

error:function(){

//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});

$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>

Here is the JSON File to create...

这是要创建的 JSON 文件...

{  
"List":[  
{  
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{  
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{  
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{  
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}

Hope this helps, thank you all above for getting me this far.

希望这会有所帮助,感谢以上所有人让我走到这一步。

回答by Dharmendra Singh

Try This Example:

试试这个例子:

$("#location").change(function(){

    var tag = $("option[value="+$(this).val()+"]", this).attr('mytag');

    $('#setMyTag').val(tag); 

});

回答by Amit-Rlogical

$("body").on('change', '#location', function(e) {

 var option = $('option:selected', this).attr('myTag');

});