鉴于以下内容:
<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>
Run Code Online (Sandbox Code Playgroud)
这不起作用...
当select更改时,我需要做什么才能将隐藏字段的值更新为myTag的值.我假设我需要做一些关于获取当前选定值的事情......?
SLa*_*aks 493
您正在向<select>元素添加事件处理程序.
因此,$(this)将是下拉本身,而不是选中<option>.
您需要找到所选的<option>,如下所示:
var option = $('option:selected', this).attr('mytag');
Run Code Online (Sandbox Code Playgroud)
tva*_*son 45
试试这个:
$(function() {
$("#location").change(function(){
var element = $(this).find('option:selected');
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
});
Run Code Online (Sandbox Code Playgroud)
Naw*_*Man 24
这是因为元素是"选择"而不是"选项",其中您有自定义标记.
试试这个:$("#location option:selected").attr("myTag").
希望这可以帮助.
试试这个:
$("#location").change(function(){
var element = $("option:selected", this);
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
Run Code Online (Sandbox Code Playgroud)
在回调函数中change(),this指的是select,而不是选中的选项.
小智 7
假设你有很多选择.这可以做到:
$('.selectClass').change(function(){
var optionSelected = $(this).find('option:selected').attr('optionAtribute');
alert(optionSelected);//this will show the value of the atribute of that option.
});
Run Code Online (Sandbox Code Playgroud)
小智 6
最简单的一个,
$('#location').find('option:selected').attr('myTag');
Run Code Online (Sandbox Code Playgroud)
如果是一种形式,则语法更简单。
var option = $('option:selected').attr('mytag')
...如果有不止一种形式。
var option = $('select#myform option:selected').attr('mytag')