有没有更好的方法来编写后代选择器?

时间:2017-06-15 05:45:44

标签: javascript

我是JS的新手,我希望根据某些条件动态删除页脚上的一个链接。 但是我的页脚嵌套在多个类下面,删除链接的代码是:

 $( ".footer .footer__container .footer__information .footer__links .footer__link").last().empty();

有没有更好的方法来编写这个嵌套多个类的特定行? 请注意:在我的原始项目文件中," .footer" class是暴露给我的文件的东西。所以我的顶级课程必须从" .footer"开始。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Delete link in a footer demo</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>
    Hello, <span>Person</span> <em>and person</em>.
</p>

<!-- footer has 3 links of which last link needs to be deleted on button press -->
<footer role="footer" class="footer">
    <div class="footer__container">
        <div class="footer__logo">
            <img src="images.png" alt="Images">
        </div>
        <div class="footer__information">
            <div class="footer__links">
                <a target="_blank" href="https://link1" aria-label="link1" class="footer__link">link1</a>
                <a target="_blank" href="https://link2" aria-label="link2" class="footer__link">link2</a>
                <a target="_blank" href="https://link3" aria-label="link3" class="footer__link">link3</a>
            </div>
        </div>
    </div>
</footer>
<button>Call empty() on above paragraph</button>

<script>
    $( "button" ).click(function() {
        $( ".footer .footer__container .footer__information .footer__links .footer__link").last().remove();
    });
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

除非您有另一部分具有类似内部类的HTML,否则您不需要具体。在这种情况下你需要的只是

$(".footer_link").last().remove(); // or .empty(), whichever you intended
相关问题