gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:14:30 27 4
gpt4 key购买 nike

我有 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 内容,则跳过,否则追加到目标。然后destination将附加到另一个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 中的 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

关于javascript - 如何将div的唯一元素附加到另一个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34650437/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com