如何使用 JavaScript 將 div 中逗號分隔的文字轉換成獨立的行?


假設以下為 div 中的逗號分隔文字 −

<div class="commaSeparated">
This,is,the,first,JavaScript,program
</div>

若要將逗號分隔文字轉換成獨立行,您需要根據逗號(,)使用 trim() 以及 split()。

例項

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="commaSeparated">
This,is,the,first,JavaScript,program
</div>
</form>
<script>
   var allTheData = document.querySelector('.commaSeparated').textContent.trim().split(',')
   var separateList = '<ul>'
   allTheData.forEach(function(value) {
      separateList += '<li>' + value + '</li>';
   });
   separateList += '</ul>';
   document.querySelector(".commaSeparated").innerHTML = separateList;
</script>
</body>
</html>

若要執行上述程式,請將檔名儲存為 “anyName.html(index.html)”,然後右擊檔案。在 VS Code 編輯器中選擇 “使用 Live Server 開啟” 選項。

輸出

這將生成以下輸出 −

更新於: 2020 年 9 月 9 日

3K+ 瀏覽

開啟你的 職業

完成課程,獲得認證

現在開始
廣告
© . All rights reserved.