动态创建Span元素

时间:2013-03-27 14:46:30

标签: javascript web

您好我正在寻找一些工作代码来创建span元素。

我的文字很简单,每个单词都按空格分隔。

我需要创建span,如下所示,以便我可以快速解除代码。如下所述,每个单词都有唯一的ID,如W1,W2等。

<p>
  <!-- I need to create span as follow so that -->
  <span id="W1">I</span>  
  <span id="W2">need</span>  
  <span id="W3">to/span>  
  <span id="W4">create</span>  
  <span id="W5">span</span>  
  <span id="W6">as</span>  
  <span id="W7">follow</span>  
  <span id="W8">so</span>  
  <span id="W9">that</span> 
</p>

感谢。

我有MS表达式web和vb studio,我可以在本地保存并继续创建的任何工具。

I see this link on web doing something.

2 个答案:

答案 0 :(得分:1)

HTML

<body>
    <p>
    </p>
</body>

的js

<script>
    var sString = "asdf sadfasd f sdfasd fasdfasdfasdf";
    var aString = sString.split(' ');

    for (var i=0;i<aString.length;i++)
    {
        document.getElementsByTagName("p")[0].innerHTML += '<span class="w' + i + '">' + aString[i] + '</span>'
    }
</script>

总是发布你的代码,即使你觉得愚蠢和错误:)

答案 1 :(得分:1)

// You either have a string 
var mysentence = "I need to do my homework";

// or a paragraph
<p id="words">I need to do my homework</p>
// get sentence
var mysentence = document.getElementById('words');


function spanify(sentence) {
  var arrayOfStrings = sentence.split(" "), newString = "";
    for (var i=0; i < arrayOfStrings.length; i++){
        newString += "<span id='W" + i + "'>" + arrayOfStrings[i] + "</span>";
        }
        return newString;
    }

// spanify the sentence
spanify(mysentence);