我正在尝试创建一个简单的小部件,允许用户选中复选框或整个div来更改其值。我有以下代码:
$(document).ready(function() {
$(document).on("click", ".inputCheck", function(event) {
event.stopImmediatePropagation();
event.preventDefault();
$(this).closest(".outter").trigger("click");
});
$(document).on("click", ".outter", function(event) {
console.log("inside");
event.stopImmediatePropagation();
event.preventDefault();
var $checkBox = $(this).find("input");
$(this).removeClass("selected");
$checkBox.prop("checked", !$checkBox.prop("checked"));
if ($checkBox.prop("checked"))
$(this).addClass("selected");
});
});

.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}

<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="outter">
<input class="inputCheck" type="checkbox">
<div>This is a test</div>
</div>
</body>
</html>
&#13;
当选择div时,它正常工作。复选框更改值和选择的新班级&#39;被添加到.outter类。当选中该复选框时,我尝试停止所有默认值和传播,然后触发与选择div以更改类值相同的代码。但是复选框保持不变。有人可以告诉我为什么这不起作用以及如何解决它?
由于
答案 0 :(得分:3)
您无需停止传播或任何其他内容。您可以检查点击是否在输入上,然后更改输入检查状态,如下所示。单击输入将自动传播到父div。您可以使用event.target
检查点击来源并采取必要的措施。
$(document).ready(function() {
$(".outter").click(function(event) {
console.log('clicked');
var $checkBox = $(this).find("input");
$(this).removeClass("selected");
if (!$(event.target).is($checkBox)) {
$checkBox.prop("checked", !$checkBox.prop("checked"));
}
if ($checkBox.prop("checked"))
$(this).addClass("selected");
event.stopPropagation();
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outter">
<input class="inputCheck" type="checkbox" />
<div id="testIt">This is a test</div>
</div>
答案 1 :(得分:0)
$(document).ready(function() {
$(document).on("click", ".inputCheck", function(event) {
event.stopImmediatePropagation();
$(this).closest(".outter").trigger("click");
});
$(document).on("click", ".outter", function(event) {
console.log("inside");
event.stopImmediatePropagation();
var $checkBox = $(this).find("input");
if ($checkBox.prop("checked"))
$(this).addClass("selected");
else
$(this).removeClass("selected");
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="outter">
<input class="inputCheck" type="checkbox">
<div>This is a test</div>
</div>
</body>
</html>