为什么我的范围内没有显示我的跨度?

时间:2019-10-09 16:01:03

标签: javascript html

我试图以内联方式显示一些跨度,就像它们是文档一样。但是,当我将span标记加载到div中时,即使根据控制台div本身包含span,它们也不会出现。不确定我是否需要自行设置跨度的额外参数?

var documentbody = document.getElementById("docbod");

/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
  var divarray = []
  var state = ["hey", "there", "how", "are", "you", "doing?"]
  for (let i = 0; i < state.length; i++) {
    span = document.createElement("span")
    span.value = state[i]
    span.id = "word" + i;
    span.classList.add("initialTextcolor")
    div.append(span)
  }
  return div
}


/* highlights a selected word within the document*/
function highlight(selection) {
  console.log("selection", selection)
  let element = document.getElementById(selection.id);
  element.classList.add("highlighted");

}
documentbody.value = splitdocintowords(documentbody)
documentbody.addEventListener("mouseup", highlight(window.getSelection()));
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>

2 个答案:

答案 0 :(得分:-1)

span.value更改为span.innerHTML = state[i]

var documentbody = document.getElementById("docbod");

/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
  var divarray = []
  var state = ["hey", "there", "how", "are", "you", "doing?"]
  for (let i = 0; i < state.length; i++) {
    span = document.createElement("span")
    span.innerHTML = state[i]
    span.id = "word" + i;
    span.classList.add("initialTextcolor")
    div.append(span)
  }
  return div
}

/* highlights a selected word within the document*/
function highlight(selection) {
  console.log("selection", selection)
  let element = document.getElementById(selection.id);
  element.classList.add("highlighted");

}
documentbody.value = splitdocintowords(documentbody)
documentbody.addEventListener("mouseup", highlight(window.getSelection()));
#docbod {
  border: 1px solid #000
}
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>

答案 1 :(得分:-1)

您已将span附加到div,但是由于设置了属性“值”(而不是innerText或innerHTML),它们内部没有任何内容

var documentbody = document.getElementById("docbod");

/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
  var state = ["hey", "there", "how", "are", "you", "doing?"]
  for (let i = 0; i < state.length; i++) {
    span = document.createElement("span")
    span.innerHTML = state[i]; //use innerText, innerHTML or textContent here
    span.id = "word" + i;
    span.classList.add("initialTextcolor")
    div.appendChild(span)
  }
}


splitdocintowords(documentbody)
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>