replaceWith()函数似乎可以无限次运行

时间:2018-10-24 04:07:28

标签: javascript jquery replacewith

我正在尝试使用jquery函数replaceWith()将具有“问题”类的现有div替换为相同的div,只是按字母顺序排序。

排序有效,替换似乎有效,尽管当我只想替换一次时,它们似乎被无限次替换了。

我想用具有相同div的类..question替换那些div,尽管只是用

排序

有关原始HTML的屏幕截图,请参见下文。请注意,共有31个div。 original HTML

这是我的JavaScript代码:

{{1}}

当我尝试加载该页面时,它用以下控制台输出无限次(似乎)替换了这些div(看似): enter image description here

排序似乎有效,但是我不希望它被无限多次附加!我只希望对这31个div进行排序并显示一次。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

代码中的主要问题在于以下两行:

(1) var unsortedQuestionItems = $('.question');
...
(2) unsortedQuestionItems.replaceWith(sortedItems);

(1)上,您选择具有问题类的每个元素(如您所说的,其中可能有很多项目),然后在 (2),您要将 replaceWith()方法应用于这些项目中的每一项,因此,每个具有 question 类的项目都将被替换为元素,这就是您多次看到排序后的数组的原因。我给您提供一个固定的示例,在该示例中可以解决此问题并进行其他修复。

$(document).ready(function()
{
    // Define the sorting function
    // NOTE: sort() is applied without converting to array.

    function getSorted(selector, attrName)
    {
        return $(selector).sort(function(a, b)
        {
            var aVal = parseInt(a.getAttribute(attrName));
            var bVal = parseInt(b.getAttribute(attrName));
            return aVal - bVal;
        });
    }

    // Get sorted and unsorted elements.

    var sortedItems = getSorted('div.question', 'data-answerCount');
    var unsortedQuestionItems = $('.question');

    console.log("Replacing unsorted question items with sorted question items");
    console.log("oldArray is of length: " + unsortedQuestionItems.length);
    console.log("newArray is of length: " + sortedItems.length);

    // Replace old unsorted elements with sorted elements.

    unsortedQuestionItems.parent().empty().append(sortedItems);

    console.log("Replacing completed.");
    var afterReplaced = $('.question');
    console.log("After replacing, the length of .question is: " + afterReplaced.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container questions-container">
  <div class="question" data-answercount="16">16</div>
  <div class="question" data-answercount="4">4</div>
  <div class="question" data-answercount="10">10</div>
  <div class="question" data-answercount="4">4</div>
  <div class="question" data-answercount="5">5</div>
</div>