Pau*_*aul 3 javascript jquery onchange
我有几个带有ids country1,country2的下拉框,...当国家/地区在下拉列表中更改时,国家/地区的值将显示在警告框中.
如果我为这样的一个框添加onchange处理程序,它工作正常:
$('#country1') .live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
Run Code Online (Sandbox Code Playgroud)
但我需要动态地为所有下拉框执行此操作,所以我尝试了:
$(document).ready(function() {
$('[id^=country]') .each(function(key,element){
$(this).live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
});
});
Run Code Online (Sandbox Code Playgroud)
这不起作用.没有语法错误,但是当更改选择的国家/地区时没有任何反应.我确信每个循环都执行了几次,并且数组包含选择框.
有什么想法吗?
谢谢,保罗
.live()存在的原因是考虑调用选择器时不存在的元素.
$('[id^=country]') .each(function(key,element){迭代具有id开头的元素country,但只遍历运行选择器时存在的元素.它对你打电话后创建的元素不起作用.each(),所以使用.live()对你没什么好处.
对该选择器使用新样式事件委托语法,它应该工作:
$(document).on('change', '[id^=country]', function(e) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
替换document为未动态生成的最近父级.
另外,请考虑向这些元素添加一个类以及该id属性.
而不是增量ID我会使用一个类.然后live不推荐使用该方法,但您可以on在最近的静态父级或document其他方面使用委托.
$('#closestStaticParent').on('change', '.country', function() {
// this applies to all current and future .country elements
});
Run Code Online (Sandbox Code Playgroud)
你不需要这样的每个循环; 加上事件被连接到所有的jQuery的集合中的元素,在这种情况下,所有.country的元素.