[英]Why isn't my checkbox change event triggered?
第一个功能将div点击转换为自定义的选中/未选中切换。 第二个功能将复选框更改转换为检查/取消检查事件(此工作正常)。
问题是,当我使用第一个函数来选中/取消选中该框时,不会调用第三个函数。 我是javascript新手,谢谢。
$(document).ready(function() {
/*
Progressive enhancement. If javascript is enabled we change the body class. Which in turn hides the checkboxes with css.
*/
$('body').attr("class","js");
/*
Add toggle switch after each checkbox. If checked, then toggle the switch.
*/
$('.checkbox').after(function(){
if ($(this).is(":checked")) {
return "<a href='#' class='toggle checked' ref='"+$(this).attr("id")+"'></a>";
}else{
return "<a href='#' class='toggle' ref='"+$(this).attr("id")+"'></a>";
}
});
/*
When the toggle switch is clicked, check off / de-select the associated checkbox
*/
$('.toggle').click(function(e) {
var checkboxID = $(this).attr("ref");
var checkbox = $('#'+checkboxID);
if (checkbox.is(":checked")) {
checkbox.removeAttr("checked");
}else{
checkbox.attr("checked","true");
}
$(this).toggleClass("checked");
e.preventDefault();
});
});
$(document).ready(function(){
$(":checkbox").change(function(){
if ($(this).is(":checked")) { $(el).layerSlider('start');
}else{ $(el).layerSlider('stop');}
});
});
要将事件添加到动态内容(在本例中为动态锚元素),则必须使用实时或实时功能。
对于1.7之前的jquery版本,您将必须使用Live函数。
$('.toggle').live("click", function (e) {
var checkboxID = $(this).attr("ref");
var checkbox = $('#' + checkboxID);
if (checkbox.is(":checked")) {
checkbox.prop('checked', false);
} else {
checkbox.prop('checked', true); //jQuery 1.6+
}
e.preventDefault();
});
从jQuery 1.7+起不推荐使用Live,从1.9+起不推荐使用Live。因此,如果您使用的是jQuery 1.9+,请使用On。
$('.toggle').on("click",function (e) {
var checkboxID = $(this).attr("ref");
var checkbox = $('#' + checkboxID);
if (checkbox.is(":checked")) {
checkbox.prop('checked',false);
} else {
checkbox.prop('checked', true); //jQuery 1.6+
}
e.preventDefault();
});
并且还使用prop函数来选中/取消选中复选框。 (道具是从jQuery 1.6添加的)
您需要在复选框上触发更改事件,而不是单击
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.