Javascript jQuery.change函数只工作一次
使用jQuery1.11.1和这段代码检测select字段值的更改,然后运行一些脚本。它只工作一次,然后就不会再工作了。它已经足够远,可以移除“可见”类,就这样Javascript jQuery.change函数只工作一次,javascript,jquery,select,Javascript,Jquery,Select,使用jQuery1.11.1和这段代码检测select字段值的更改,然后运行一些脚本。它只工作一次,然后就不会再工作了。它已经足够远,可以移除“可见”类,就这样 var oatChoice; $('#cereal').change(function(){ oatChoice = ($(this).val()); $('.oats').removeClass('visible').delay(1000).queue(function() { imageURL
var oatChoice;
$('#cereal').change(function(){
oatChoice = ($(this).val());
$('.oats').removeClass('visible').delay(1000).queue(function() {
imageURL = '/assets/images/layers/oats-' + oatChoice;
imgSwitch('.oats',imageURL);
$('.oats').addClass('visible');
});
});
imgSwitch = function(div,imgURL){
$(div + ' img').remove();
$(div).append('<img src="' + imgURL + '.png"/>');
}
我在下面的html中运行此代码:
<div class="layer oats">
<img src="/assets/images/layers/oats-applecinnamon.png" alt="">
</div>
<select name="cereal" id="cereal" class="form-control">
<option value="">- Select A Cereal -</option>
<option value="applecinnamon">Apple Cinnamon Oatmeal</option>
<option value="vanilla">Vanilla</option>
</select>
我在这里创作了一把小提琴。。图像丢失,但您可以看到它在第一次恢复后停止工作。尝试以下操作:
$('#cereal').unbind('change').change(function(){
//the rest of your code
})
编辑:您可以尝试将变量和函数移出全局范围,并使用每个更改操作重新呈现函数,如下所示:
(function(main, $, undefined){
Template = {
oatChoice:null,
render: function(){
Template.setup.changeActions();
}
setup: {
changeActions : function(){
$('#cereal').unbind('change').change(function(){
Template.oatChoice = ($(this).val());
$('.oats').removeClass('visible').delay(1000).queue(function() {
imageURL = '/assets/images/layers/oats-' + Template.oatChoice;
Template.imgSwitch('.oats',imageURL);
$('.oats').addClass('visible');
});
Template.render();
});
}
},
imgSwitch : function(div,imgURL){
$(div + ' img').remove();
$(div).append('<img src="' + imgURL + '.png"/>');
},
}
}(window.main = window.main || {}, jQuery));
你能在JS FIDDLE中发布你的代码吗?更改仅限于,和。你在听什么改变?还有更多的HTML吗?