[英]Get specific text from a div and make into a link
我不確定這是否可能,我一直在嘗試使用 jQuery 但還沒有走遠。
我想從 div 中獲取文本並將它們轉換為鏈接。
問題是我希望這 3 個名稱成為單獨的鏈接,例如 href="/staff/john"、href="/staff/sarah" 和 href="/staff/mike"
任何幫助將非常感激。
<div id="container"> john, sarah, mike </div>
像這樣 - 不需要 jQuery
const container = document.getElementById("container"); container.innerHTML = container.textContent.split(",").map(name => `<a href="/staff/${name.trim().toLowerCase().replaceAll(" ","-")}">${name.trim()}</a>`).join(", ")
<div id="container"> John Doe, Sarah Doe, Mike Hunt </div>
但如果你想要 jQuery 你可以做
$("#container").html(function() { return $(this).text().split(",").map(name => `<a href="/staff/${name.trim().toLowerCase().replaceAll(" ","-")}">${name.trim()}</a>`).join(", ") })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> John Doe, Sarah Doe, Mike Hunt </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.