繁体   English   中英

如何将div的唯一元素附加到另一个div

[英]How to append unique element of div to another div

我有2个div,例如<div id="destination" runat="server"></div><div class="errorDiv"></div>

我写了一个jQuery函数

 $(document).each(function () {
            if ($("#destination").find("div").html() !== $(".errorDiv").html()) {
                $("#destination").append($(".errorDiv"));
                $("#error").append($("#destination"));
            }
        }).change();

在此功能中,如果目标div包含errorDiv内容,则跳过,否则追加到目标。 然后目标将追加到另一个div。 但是,我的支票不起作用。 如何仅添加div的唯一元素? errorDiv内容在ASP页中生成,并且该内容是通用的。

页面运行时,我捕获了一些错误消息,并且想要将有关这些消息的某些内容附加到目标div。 例如; 如果我抓住

 <div class="errorDiv">A</div>
 <div class="errorDiv">A</div>
 <div class="errorDiv">B</div>
 <div class="errorDiv">B</div>
 <div class="errorDiv">A</div>
 <div class="errorDiv">C</div>

我只想附加的内容

 <div class="errorDiv">A</div>
 <div class="errorDiv">B</div>
 <div class="errorDiv">C</div>

div至目标div。

但是,使用我的功能,所有div都会被追加。

因此,这听起来像是您获得了新的.errorDiv#destination仅当尚不存在等效文本时才希望将它们添加到#destination

为此,您需要遍历#destination的div,而不仅仅是查看一个的HTML。 看评论:

$(document).each(function() {   // <== Calling .each on $(document) makes no sense
    // Get an array of the currently-known errors in destination
    var errors = $("#destination div").map(function() {
        return $(this).html();
    }).get();

    // Loop through the "new" errors
    $(".errorDiv").each(function() {
        // Is the text of this error already in the destination?
        if ($.inArray($(this).html(), errors) == -1) {
            // No, add it
            $("#destination").append(this);
            $("#error").append($("#destination")); // <== This seems very strange
        }
    }
}).change();                   // <== Triggering the change event on document seems odd

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM