jQuery选择更改不触发 [英] Jquery select change not firing
问题描述
我需要捕捉的时候一个选择框的变化,应该是简单的!
I need to capture when a select box changes, should be simple!
$('#multiid').change(function(){
alert('Change Happened');
});
但是它不起作用,我怀疑问题是只有在需要时才创建它的文档上不存在选择框,因此我将其以HTML创建为空,并用代码填充了它作为测试,但这没有也不行.
But it does not work, I suspected the problem is that the select box does not exist on document ready it is created only if needed, so I created it empty in HTML, populated it with code as a test but that didn't work either.
function buildmulti(id,name,price) {
// build action items for action bar
var optlist = $('<select></select>').attr('id', 'multiid').attr('name', 'multiid');
optlist.append('<option value="0">Select Size</option>');
$.each(option, function(index, val) {
if(val.prodID *1 == id * 1) {
v = val.ID;
fprice = price * 1 + val.pricechange * 1;
t = name + ' - ' + val.variation + ' - ' + currency + (fprice).toFixed(2);
optlist.append('<option value="' + v + '">' + t + '</option>');
}
})
$('#addbasket').append(optlist);
};
可能是另一个不合适的支架,但是我找不到它!
it's probably another bracket out of place, but I can't find it!
推荐答案
尝试
$(document).on('change','#multiid',function(){
alert('Change Happened');
});
由于选择框是通过代码生成的,因此您必须使用事件委托,而不是$(document)
您可以拥有最接近的父元素.
As your select-box is generated from the code, so you have to use event delegation, where in place of $(document)
you can have closest parent element.
或
$(document.body).on('change','#multiid',function(){
alert('Change Happened');
});
更新:
第二个方法工作正常,选择器还有另一处更改,以使其正常工作.
Second one works fine, there is another change of selector to make it work.
$('#addbasket').on('change','#multiid',function(){
alert('Change Happened');
});
理想情况下,我们应该使用$("#addbasket")
,因为它是最接近的父元素[正如我上面提到的].
Ideally we should use $("#addbasket")
as it's the closest parent element [As i have mentioned above].
这篇关于jQuery选择更改不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!