我正在用JQuery做一些实验,这发生了,
有一个复选框,如果用户点击它,那么<p>
标记将附加到最近的div中,如果用户取消选中它,则<p>
标记将被删除。
当我$(obj).closest("div").append
段落要追加到下一个最接近的div时,但当我取消它时,它删除了整个div。我不想考虑删除子div,当我正在做$(obj).closest("div").append
时我没有追加到同一个div而是下一个div,当我删除它时也删除整个复选框div。任何人都可以解释一下吗?
$("#checkObxId").click(function() {
var result = onCheckChange(this);
addDynamicRow(this, result);
});
function onCheckChange(obj) {
$(obj).val(false);
var result = false;
if ($(obj).prop("checked") == true) {
$(obj).val(true);
result = true;
}
return result;
}
function addDynamicRow(obj, result) {
if (result) {
$(obj).closest("div").append("<p>This is input</p>");
} else {
$(obj).closest("div").empty();
}
}
HTML:
<form id="smsForm">
<div class="checkbox">
<label> <input type="checkbox" name="smsToOrganization"
id="smsToOrganization"> SMS TO Organization
</label>
</div>
<div></div>
<div class="checkbox">
<label> <input type="checkbox" name="smsToClient"
id="smsToClient">Sms To Clien
</label>
</div>
<div></div>
<div class="checkbox">
<label> <input type="checkbox" name="smsToBod" id="smsToBod">
Sms To BOD
</label>
</div>
<div></div>
<div class="checkbox">
<label> <input type="checkbox" name="smsToAnyone"
id="smsToAnyone"> SMS To Anyone
</label>
</div>
<div></div>
</form>
答案 0 :(得分:1)
答案 1 :(得分:0)
$(function() {
$("input:checkbox").click(function() {
if (this.checked) {
$(this).closest("div").append("<p id='test'>This is input</p>"); //append id="test" nearest code...
} else {
$('#test').remove(); //remove id="test" closest code...
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label> <input type="checkbox" name="smsToOrganization"
id="smsToOrganization"> SMS TO Organization
</label>
</div>
<div></div>
<div class="checkbox">
<label> <input type="checkbox" name="smsToClient"
id="smsToClient">Sms To Clien
</label>
</div>
<div></div>
<div class="checkbox">
<label> <input type="checkbox" name="smsToBod" id="smsToBod">
Sms To BOD
</label>
</div>
<div></div>
<div class="checkbox">
<label> <input type="checkbox" name="smsToAnyone"
id="smsToAnyone"> SMS To Anyone
</label>
</div>
<div></div>
注意: - 你需要给附加id提供名称,所以我们可以通过它的id名称来删除....