亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試定位無序列表中的特定數字 LI 項目并附加 html

嘗試定位無序列表中的特定數字 LI 項目并附加 html

FFIVE 2024-01-03 14:27:08
問候堆棧溢出,我已將 html 代碼保存為名為“test”的 js 變量。然后,我嘗試定位特定的(第 5 個)li 項目,并將 HTML 附加到該項目下方的一行中:var target = $("ul[class='productWrapper']>li:nth-child(5)"); $(test).insertAfter($(target));我相信我在嘗試定位 LI 元素時遇到語法問題,并且不確定 insertAfter 是否是用于此任務的正確方法。歡迎您提出所有想法!
查看完整描述

1 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

我冒昧地在它周圍添加了更多背景信息,它似乎工作得很好。我稍微改變了你的語法,但沒有改變所討論的主線。有兩個元素只是為了清楚地表明 .insertAfter() 擊中了正確的元素,而且只有那個元素。


這是底部帶有腳本的 HTMl。


<html dir="ltr">

<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="http://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>

頁面完全加載并且腳本完成后,這就是頁面的外觀,我相信這就是您的想法。

https://img1.sycdn.imooc.com/6594fe610001f28c01520355.jpg

查看完整回答
反對 回復 2024-01-03
  • 1 回答
  • 0 關注
  • 143 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號