请不要将此标记为重复!这是唯一纯粹的JAVASCRIPT方法,具有个人ID
如何将大块文本拆分为具有以下ID的单个跨度:
<span class="word" id="word0">Breaking </span>
<span class="word" id="word1">News. </span>
<span class="word" id="word2">Spring </span>
<span class="word" id="word3">is </span>
<span class="word" id="word4">here </span>
<span class="word" id="word5">to </span>
<span class="word" id="word6">stay. </span>
如果输入是“突发新闻。春天来了。”
我想从特定div获取输入并将其输出到同一个div中。请不要使用jquery。
编辑:感谢Scott Marcus,他给了我这段代码:/* hw3a.js */
// your solution here
var button = document.getElementById('divideTranscript');
button.onclick = spanify();
var s = document.getElementById('transcriptText').innerHTML;
function spanify() {
var arry = s.split(" ");
var arry = s.split(/\s+/); // This will split on any group of whitespaces
var output = "";
var len = arry.length;
for(var i = 0; i < len; ++i) {
output += "<span class='word' id='word" + i + "'>" + arry[i] + "</span>" ;
}
s.innerHTML = output;
}
但它不起作用?
答案 0 :(得分:1)
var s = "Breaking News. Spring is here to stay.";
var arry = s.split(" "); // This will split on all single whitespaces
var arry = s.split(/\s+/); // This will split on any group of whitespaces
var output = "";
var len = arry.length;
for(var i = 0; i < len; ++i){
output += "<span id='word" + i + "'>" + arry[i] + "</span>" ;
}
alert(output);
// Or, to be more core DOM compliant
var d = document.createElement("div");
for(var i = 0; i < len; ++i){
var sp = document.createElement("span");
sp.setAttribute("id", "word" + i);
sp.textContent = arry[i];
d.appendChild(sp);
}
alert(d.innerHTML);