当单击页面上的复选框时,我会抓住它包含元素并将整个块附加到页面的另一部分。喜欢这个:
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = $(check).attr("checked"),
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
favelist = $(".favourites .content");
if (checked === "checked") {
$(favelist).append(parentContent);
}
});
我希望在将新复选框粘贴到收藏夹列表时选中它。我可以对parentContent做些什么 - 它包含复选框和周围元素的HTML块 - 以便在附加时已经选中它?
字符串附加到 favelist,你可以立即附加一个 jQuery 元素。通过这样做,将通过 DOM 设置的所有属性和样式都将保留,例如 checked
。
这意味着您可以同时删除$("<div />").append(
和).html()
。
生成的代码如下所示。
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = $(check).attr("checked"),
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("#food-" + id).clone(),
favelist = $(".favourites .content");
if (checked === "checked") {
$(favelist).append(parentContent);
}
});
它也会更快。
试试这个,
checked = this.checked,
或
checked = $(check).prop("checked"),
代替
checked = $(check).attr("checked"),
和编纂一样,
if (checked === true) {
$(favelist).append(parentContent);
}
完整代码,
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = this.checked,
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
favelist = $(".favourites .content");
if (checked === true) {
$(favelist).append(parentContent);
}
});
我会给这个老大学尝试......
$('.favourite').on('click','[type="checkbox"]',function(){
var chk = this.checked,
id = this.id.split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
$favelist = $(this).find(".content");
if (chk === "checked") {
$favelist.append(parentContent).find('input[type="checkbox"]').prop('checked');
}
});
这增加了一些委派操作,并使用 checked
和 id
的原版 JS 版本来实现性能目的。它还消除了您使用favelist
进行的双重包装。