我正在使用一个函数将文本区中的字符串添加到一个数组中,然后使用innerHTML将它们打印到DOM中(我在这里学到的)。该函数是通过modal上的一个按钮调用的。
function setArray( ){
let textAreaElement = document.getElementById('textToArray');
let listArray = textAreaElement.value.trim().split('\n');
console.log(listArray);
document.getElementById('PrintToSidebar').innerHTML = listArray.join("<p>");//I want to add IDs in the <p> tags created here
modal.style.display = "none";
}
这似乎运行良好,但我还想为每个单独的<p>
设置一个ID,其中ID等于字符串值。
例如,如果listArray = ["Line 1", "Line 2"],那么我期望的innerHTML将会是:
<p id="line-1">Line 1</p>
<p id="line-2">Line 2</p>
我的搜索结果显示我需要使用setAttribute方法。但我也在考虑首先遍历listArray。
我只学习了几天的Javascript(实际上是完全新手),详细的解决方案会非常有帮助。谢谢!
id
实际上是无效的(https://dev59.com/vWw15IYBdhLWcg3wIoVM#7873035),因为`id`中不能有空格。不过,可以通过[Javascript Replace](https://www.w3schools.com/jsref/jsref_replace.asp)函数轻松消除空格。 - EGC