尝试在无序列表中定位特定编号的LI项目并附加html

问题描述 投票:0回答:1

问候堆栈溢出,

我将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个回答
0
投票

我想,@ 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>

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

screen after js executes

© www.soinside.com 2019 - 2024. All rights reserved.