jQuery - 从div中删除具有特定类的所有锚标记

时间:2013-04-22 12:16:56

标签: jquery

在某些情况下,并且出于超出此问题范围的原因,锚点会重复出现。这是一个示例div:

<div class="unifyRepeat listing">
    <a class="businessAnchor" name="abcchildcareandlearningcenter"></a>
    <a class="businessAnchor" name="abcchildcareandlearningcenter"></a>
    <a class="businessAnchor" name="abcchildcareandlearningcenter"></a>
    <a class="businessAnchor mceItemAnchor" name="abcchildcareandlearningcenter"></a>
    <table class="tblListing">
        <tbody>
            <tr>
                <td>
                    <p class="bold">ABC Child Care and Learning Center</p>
                    <p>Jane Smith</p>
                    <p>(555) 555-1234</p>
                </td>
                <td>
                    <img alt="" src="images/ABCchildcare.jpg">
                </td>
                <td>
                </td>
            </tr>
        </tbody>
    </table>
    <a class="linkToTop" href="#top">^ Top</a>
</div>

这是附加锚点并尝试删除任何现有锚点的jQuery:

$('#businessListings div.listing').each(function() {
    var name = $(this).find('p:first').text(),
        cleanedName = name.replace(/\W/g, '').toLowerCase();

    $('ul#businessListingLinks').append('<li><a href="#' + cleanedName + '">' + name + '</a>');

    var anchor = '<a class="businessAnchor" name="' + cleanedName + '"></a>';
    $(this).remove('a.businessAnchor');
    //$(this).each('a.businessAnchor').remove();
    $(this).prepend(anchor);
});

我认为remove()行会选择带有“businessAnchor”类的所有锚标记,但事实并非如此。

正如您所看到的,我尝试了each()函数,但这不起作用。我不确定是不是因为我没有正确实施,或者其他原因。

1 个答案:

答案 0 :(得分:7)

试试这个:

$(this).find('a.businessAnchor').remove();

因为从标记开始,a.businessAnchor似乎是div的直子,所以你也可以这样做:

$(this).children('a.businessAnchor').remove();
相关问题