将复选框的值设置为“选中”,当附加到页面的另一部分时

Set value of a checkbox to "checked" when appending to another part of page

本文关键字:分时 另一部 设置 复选框 选中      更新时间:2023-09-26

当单击页面上的复选框时,我会抓住它包含元素并将整个块附加到页面的另一部分。喜欢这个:

  $('.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');
    }
});

这增加了一些委派操作,并使用 checkedid 的原版 JS 版本来实现性能目的。它还消除了您使用favelist进行的双重包装。

相关文章: