如何将多个body onChange-functions的执行限制为真正仅在选择器抓取时运行?
$('body').on('change',$selectRadios,function(e){
// do something and stuff like
$btnNext.removeAttr('disabled');
console.log('I should only run if I change $setupRadios')
}
$('body').on('change',$selectCheckboxes,function(e){
// do something else and stuff without interfering with the first onChange-function like
$btnNext.attr('disabled',true);
console.log('I should not run if I change $setupRadios');
}
如果我这样做,如果我更改$ selectRadios,btnNext将不会重新启用,但它将保持禁用状态(它实际上运行第二个函数,因为我在控制台中可以看到它记录«我不应该运行如果我也改变$ setupRadio»
更新我必须使用来自正文的事件委派而不是直接缓存元素,因为$ selectRadio和$ selectCheckboxes会动态地添加到页面中,并附带更多脚本
更新2: $ selectRadio和$ selectcheckboxs正在通过以下方式添加:
function addTeam() {
for(var i = 0; i < resultSetupCount; i++) {
$('.js-setup ul').append($('<li tabindex="0"><input class="js-setupRadio" type="radio" id="setup'+(i+1)+'" name="setup" value="setup'+(i+1)+'" data-setup0="'+resultSetupGoalie[i]+'" data-setup1="'+resultSetupAbwehr[i]+'" data-setup2="'+resultSetupVorne[]+'" data-trck="setup-'+resultSetupTrck+'-clicked" tabindex="-1" /><label for="setup'+(i+1)+'"><img alt="" src="'+resultSetupImg[i]+'" srcset="'+resultSetupImg[i]+' 1x, '+resultSetupImg2x[i]+' 2x" /><span>'+resultSetupName[i]+'</span></label></li>'));
}
}
- &GT;见.js-setupRadio
答案 0 :(得分:1)
如果您需要理清事件期间实际更改的内容,请使用event.target
。您应该能够将警报替换为您的函数,它应该仅作为被点击的元素作为上下文。
$(function() {
var $inputs = $('input');
$('#set').on('change', $inputs, function(e) {
var changed = e.target;
$inputs.each(function(index, element) {
var ele = this.className;
if (this == changed) {
alert(ele+index+' has changed');
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="set">
<input class="chk" type="checkbox">
<input class="chk" type="checkbox">
<input class="chk" type="checkbox">
<input class="chk" type="checkbox">
<input class="rad" type="radio" name="rad1">
<input class="rad" type="radio" name="rad1">
<input class="rad" type="radio" name="rad1">
<input class="rad" type="radio" name="rad2">
<input class="rad" type="radio" name="rad2">
<input class="rad" type="radio" name="rad2">
</fieldset>
&#13;
答案 1 :(得分:0)
我可以通过测试e.target是否具有来自$ selectRadios OR $ selectCheckboxes的类来解决它,并且如果为true则仅运行函数的内容:
$(document).on('change',$setupRadios,function(e){
var $that = $(e.target);
if ($that.hasClass('js-setupRadio')){
// do something and stuff like
$btnNext.removeAttr('disabled');
console.log('I should only run if I change $setupRadios')
}
});
$('body').on('change',$selectCheckboxes,function(e){
var $that = $(e.target);
if ($that.hasClass('js-checkbox')){
// do something else and stuff without interfering with the first onChange-function like
$btnNext.attr('disabled',true);
console.log('I should not run if I change $setupRadios');
}
});