【发布时间】:2012-09-27 19:02:29
【问题描述】:
我已经查看并尝试了有关此主题的许多答案,但似乎找不到有效的解决方案。我可能会遗漏一些明显的东西,在这种情况下我很抱歉,但这是我的问题:
我有一个嵌套在 DIV 元素中的复选框,这个 DIV 元素附加了一个 jQuery click 事件,然后检查复选框是否被选中,然后选中/取消选中它。根据它是否已被选中/取消选中,然后将变量发送到 PHP 脚本以添加到会话变量中。
当它是被单击的 DIV 时,这一切都很好,但是当单击复选框时,我认为会发生一些冒泡,因为它每次都会触发取消选中复选框的事件。我尝试使用附加到复选框单击事件的stopPropogation(); 和preventDefault();,但无济于事。
这里有一些示例代码可以尝试使这一点更清楚:
复选框 HTML 代码:
<div class='bundle_offer' id='bundle_offer_0'>
<input type="checkbox" />
</div>
点击功能:
// Click function on bundle offer div to add booster
$(".bundle_offer").click(function (event) {
// IF its not the checkbox clicked, send over the div id
if (event.target.type !== 'checkbox') {
var bundle_offer_div_id = "#"+this.id;
bundle_offer_click(bundle_offer_div_id);
}
// ELSE find div id and send it
else{
var bundle_offer_div_id = $(this).closest(".bundle_offer").attr("id");
bundle_offer_div_id = "#"+bundle_offer_div_id;
bundle_offer_click(bundle_offer_div_id);
}
}); // end bundle offer click function
bundle_offer_click 函数只需获取单击的 DIV 的 id,找到复选框,选中/取消选中它,然后通过 AJAX 将适当的变量发送到 PHP 脚本。
编辑:
我设法通过稍微调整逻辑来解决问题,这是我将其更改为:
// Click function on bundle offer div to add booster
$(".bundle_offer").mouseup(function (event) {
// Get whether checked or not
var isChecked = $(this).find('input').is(':checked');
// IF its not the checkbox clicked
// check/uncheck
// send over the div id
if (event.target.type !== 'checkbox') {
if(isChecked == false){
// Check
$(this).find('input').attr('checked',true);
}
else{
// Uncheck
$(this).find('input').attr('checked',false);
}
var bundle_offer_div_id = "#"+this.id;
bundle_offer_click(bundle_offer_div_id, isChecked);
}
// ELSE find div id and send it
else{
var bundle_offer_div_id = $(this).closest(".bundle_offer").attr("id");
bundle_offer_div_id = "#"+bundle_offer_div_id;
bundle_offer_click(bundle_offer_div_id, isChecked);
}
}); // end bundle offer click function
主要区别在于使用 mouseup 函数,并在 mouseup 函数中执行检查/取消选中复选框的逻辑,而不是 bundle_offer_click 之一。
【问题讨论】:
-
为什么你把你的复选框包装到
DIV??你为什么不给你的复选框定义一个类或ID并捕捉它的事件??? -
我把它包装到了一个DIV中,因为上面的代码被简化了,实际上DIV中还有其他东西,然后被拉到bundle_offer_click函数中传递给PHP脚本
标签: javascript jquery html checkbox click