0

Hello I am looking for some working code to create span elements.

My text is simple each word is seperated by space.

I need to create span as follow so that I can lift the code quickly. As mention below each word has unique id as W1, W2, etc.

<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>

Thanks.

I have MS expression web and vb studio, any tool I can keep locally and keep creating.

I see this link on web doing something.

4

2 回答 2

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);
于 2013-03-27T15:12:12.360 回答
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>

并且总是发布你的代码,即使在你看来它是愚蠢和错误的 :)

于 2013-03-27T15:01:00.870 回答