jquery $(document) on change value in the class 的选择框之一想要提醒当前选择框的选定选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27478103/
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
jquery $(document) on change value in one of select boxes of the class want to alert selected option of current select box
提问by Andris
Have one default select box inside a span
有一个默认选择框内 span
Example is here http://jsfiddle.net/pzphbnxb/18/
示例在这里http://jsfiddle.net/pzphbnxb/18/
<span id="all_locations">
<select name="united_kingdom" id="united_kingdom" class="location" >
<option value="blank">Select</option>
<option value="england">England</option>
</select>
</span>
1) Click on select box and change value.
1) 单击选择框并更改值。
2) As result get to display next select box
2)结果显示下一个选择框
3) If i click on the next select box, i want to alert (for example) id
of the clicked select box. But i see alert of the select box above.
3)如果我点击下一个选择框,我想提醒(例如)id
点击的选择框。但我看到上面选择框的警报。
Here is jquery
这是jquery
$(document).on('change', '.location', function(){
$('#all_locations').append('<select name="loc_in_england" id="loc_in_england" class="location" ><option value="blank">Select</option><option value="london">London</option>');
alert ( $('.location').find(":selected").val() + ' selected val' );
alert( $(".location").attr('id') + ' select id' );
}); //$(document).on('change'
I mean, i clicked '.location'
, clicked certain select box, i must get attr('id')
of clicked class. Why i get attr('id')
of class of the first select box?
我的意思是,我点击了'.location'
,点击了某个选择框,我必须得到attr('id')
点击类。为什么我得到attr('id')
第一个选择框的类?
Do i need to use something like .closest
to get id of clicked select box? If .closest
, then closest to what?
我需要使用类似的东西.closest
来获取点击选择框的 id 吗?如果.closest
,那么最接近什么?
回答by Mohamed-Yousef
use $(this)
instead of $('.location')
使用$(this)
代替$('.location')
$(document).on('change', '.location', function(){
// alert('test');
$('#all_locations').append('<select name="loc_in_england" id="loc_in_england" class="location" ><option value="blank">Select</option><option value="london">London</option>');
alert ( $(this).find(":selected").val() + ' selected val' );
alert( $(this).attr('id') + ' select id' );
}); //$(document).on('change'
回答by SimarjeetSingh Panghlia
http://jsfiddle.net/pzphbnxb/22/
http://jsfiddle.net/pzphbnxb/22/
Try this
尝试这个
alert ($(this).find(":selected").val() + ' selected val' );
alert( $(this).attr('id') + ' select id' );