为什么.clone()多次复制元素?

时间:2014-04-29 19:16:19

标签: jquery

我有一系列包含UL的div。在每个UL中,我需要更改特定LI的文本并从另一个元素中克隆内容。

到目前为止,我已经能够做到这一点。但是,我无法弄清楚克隆元素(.calDesc span)被复制的原因。有关为何发生这种情况的任何想法?是否有解决方法?

<!-- LINE ITEM -->
<div class="rateTypeLineItems">
    <!-- Non-Best Flex Rate -->
    <div class="regularRates roomsView"> <span>Advance Saver Rate & Deals</span>

    </div>
    <!-- Best Flexible Rate -->
    <div class="regularRates roomsView">
        <input name="upsellParentRateCode" type="hidden" value="IGCOR">
        <div class="upsellHeader"> <span class="groupHeader">Best Flexible Rate &amp; Deals</span>

        </div>
        <div class="defaultRateInfo">
            <div>
                <ul>
                    <li style="font-weight: bold; color: rgb(240, 118, 5);">Free Cancellation From <span>May-29-2014 to May-30-2014</span>
                    </li>
                    <li>No deposit required</li>
                    <li>Breakfast included</li>
                    <li>Most popular rate</li>
                    <li>View Rate Details</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="regularRates roomsView"> <span> There is no rate for this room</span>

    </div>
</div>
<!-- CONTENT THAT IS BEING CLONED -->
<p class="calDesc" style="margin:40px 0; background:red; color:white;"><span>May-29-2014 &nbsp;to&nbsp; May-30-2014
  &nbsp;&nbsp;</span> &nbsp; • &nbsp; 1&nbsp;Adult, 1&nbsp;Room &nbsp; • &nbsp; <a class="selectDatesControl" href="#selectDatesForm" id="editDate" name="editDate" title="Select to change your search">Change Search</a></p>

//move each Best Flex div above all siblings
$('.rateTypeLineItems').each(function () {
    $(this).find('.regularRates.roomsView').has(':input[value="IGCOR"]').prependTo(this);
});

//find and change date information
$('.rateTypeLineItems').each(function () {
    $(this).find('.upSellContainer .defaultRateInfo div ul li:contains("Refund")').text('Free Cancellation From ').css({
        'font-weight': 'bold',
            'color': '#F07605'
    });

});

//find each parent, clone date range and insert after .defaultRateInfo
$('.defaultRateInfo li:contains("Free Cancellation From ")').each(function () {
    $('.calDesc span').clone().appendTo('.defaultRateInfo li:contains("Free Cancellation From ")');
});

这是指向Fiddle的链接。

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为您在每次迭代时都重新选择了li。

.appendTo('.defaultRateInfo li:contains("Free Cancellation From ")')

你应该以当前的li为目标。

.appendTo(this)

http://jsfiddle.net/7e45N/8/(我删除了已经在li中的额外范围,不确定为什么要开始)