jQuery-从选定的选项获取自定义属性 [英] jQuery - getting custom attribute from selected option
本文介绍了jQuery-从选定的选项获取自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下内容:
<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>
那行不通...
当更改选择内容时,我需要怎么做才能将隐藏字段的值更新为myTag的值.我假设我需要做一些事情来获取当前选定的值...?
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...?
推荐答案
您正在将事件处理程序添加到<select>
元素.
因此,$(this)
将是下拉列表本身,而不是所选的<option>
.
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
您需要找到所选的<option>
,如下所示:
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
这篇关于jQuery-从选定的选项获取自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文