【问题标题】:Attempting to target a particular number LI item in an unordered list and append html尝试在无序列表中定位特定编号的 LI 项目并附加 html
【发布时间】:2020-04-17 10:22:46
【问题描述】:

问候stackoverflow,

我已经将 html 代码保存为名为“test”的 js 变量。

然后我试图定位一个特定的(第 5 个)li 项目并将 HTML 附加到该行下方的一行中:

var target = $("ul[class='productWrapper']>li:nth-child(5)");

$(test).insertAfter($(target));

我相信我在尝试定位该 LI 元素时遇到了语法问题,并且我不确定 insertAfter 是否是用于此任务的正确方法。

欢迎您的所有想法!

【问题讨论】:

  • 看问题的语法高亮。你没有正确地转义你的引号,所以这是一个语法错误。

标签: javascript jquery html html-lists targeting


【解决方案1】:

我认为你所拥有的一切都是对的,@JoeG。 我冒昧地在它周围添加了更多上下文,它似乎工作得很好。我稍微改变了你的语法,但不是有问题的主线。有两个元素只是为了清楚地表明 .insertAfter() 击中了正确的一个,并且只有那个。

这是底部带有脚本的 HTML。

<html dir="ltr" lang="en-US">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
    <style>
        body { display: flex; flex-direction: column; }
        ul { display: inline-block; list-style-type: none; text-align: left; background: #ccc; border-radius: 1rem; padding: 1rem; margin: 2rem auto; }
        .inserted { color: green;}
    </style>
</head>
<body>
    <ul class="productWrapper">
        <li>First</li>
        <li>Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
        <li>Sixth</li>
    </ul>
    <ul class="someOtherClass">
        <li>Other First</li>
        <li>Other Second</li>
        <li>Other Third</li>
        <li>Other Fourth</li>
        <li>Other Fifth</li>
        <li>Other Sixth</li>
    </ul>

    <script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        const $target = $(`ul[class='productWrapper']>li:nth-child(5)`)
        const $test = $(`<li class='inserted'>Inserted after fifth</li>`);
        $test.insertAfter($target);
    </script>
</body>
</html>

在页面完全加载并且脚本完成后,这就是页面的外观,我相信这就是您的想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2021-10-15
    • 2018-05-24
    相关资源
    最近更新 更多