【问题标题】:Span in Loop Javascript跨度循环Javascript
【发布时间】:2014-05-01 03:46:42
【问题描述】:

我有密码

function splitString(stringToSplit, separator) {

var str= "It’s that time of year when you clean out your closets, dust off shelves, and spruce up your floors. Once you’ve taken care of the dust and dirt, what about some digital cleaning? Going through all your files and computers may seem like a daunting task, but we found ways to make the process fairly painless."
var myArray = stringToSplit.split(" ")



for (var i=0; i < myArray.length; i++)
{

}
var yourSpan = document.createElement('span');
yourSpan.innerHTML = "";

var yourDiv = document.getElementById('divId');
yourDiv.appendChild(yourSpan);

yourSpan.onmouseover = function () {
    alert("On MouseOver");

}

对于 html 我有

<div id="transcriptText"> It’s that time of year when you clean out your
closets, dust off shelves, and spruce up your floors. Once you’ve taken
care of the dust and dirt, what about some digital cleaning? Going
through all your files and computers may seem like a daunting task, but
we found ways to make the process fairly painless.</div>
<br>
<div id="divideTranscript" class="button">&nbsp;Transform the
Transcript!&nbsp; </div>T

我需要在循环内创建跨度, 我需要创建一个 span,将 class 和 id 属性(每个单词都不同 - 它包括数组 (i) 的索引)添加到 span 元素,在 span 内添加单词,添加 mouseover/mouseout 事件侦听器到跨度,将跨度添加到原始div。 任何人都可以帮助我吗?我只是不确定我应该如何进行这些最终更改。

【问题讨论】:

    标签: javascript


    【解决方案1】:
    var yourDiv = document.getElementById('divId');
    for (var i = 0; i < myArray.length; i++) {
        var yourSpan = document.createElement('span');
        yourSpan.innerText = myArray[i];
        yourSpan.id = "yourspan_" + i;
        yourSpan.className = "yourclass";
        yourDiv.appendChild(yourSpan);
        yourSpan.onmouseover = function () {
            alert("On MouseOver");
        }
    }
    

    【讨论】:

      【解决方案2】:
      for (let i = 0; i < raceTraits.ability.length;i++){
              document.getElementById("Race").innerHTML +=  "<span id =" + i + ">" + "</span>";
      }
      
      /*you could use the value in the for loop and plugin "i" to make this easier*/
      

      【讨论】:

        猜你喜欢
        • 2020-12-13
        • 2014-03-09
        • 2020-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 1970-01-01
        相关资源
        最近更新 更多