我们的任务是通过让用户在文本字段中输入单词然后替换 html 页面中存在的隐藏段落中的单词来基本上制作 Madlib。我们必须使用 JavaScript 和 CSS。
html页面中的段落:
<span id="story" display="hidden">
Rain was still lashing the windows, which were now <span id="adjs1">__adjective__</span>, but inside all looked bright and cheerful. The firelight glowed over
the countless <span id="adjs2">___adjective___</span> <span id="plnouns">___plural_noun___</span> where people sat <span id="verbs1">___verb_with_ing___</span>
, talking, doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a <span id="foods">___food___</span> to a
<span id="monsters1">___monster___</span>. Fred had "rescued" the <span id="adjs3">___adjective___</span>, fire-dwelling <span id="monsters2">___monster___</
span> from a Care of Magical Creatures class and it was now<span id="verbs2">___verb_with_ing___</span> gently on a table surrounded by a knot of curious peopl.
</span>
一切都很顺利,直到我一直没有得到我想要的结果。
function generateMadlib(){
// Display the story. The story is initially hidden.
document.getElementById("story").style.display = "inline";
// Get the words from the textboxes.
var formElements = $("#madlibForm :text");
// Find the word locations on the hidden paragraph.
var storyWords = $("#story span");
// Replace word loc values with with formElement values
for (var i = 0; i < formElements.length; i++)
{
storyWords.eq(i).innerHTML = formElements.eq(i).val();
}
}
这一行
storyWords.eq(i).innerHTML = formElements.eq(i).val();
不会更改段落内跨度内的值。 (代码在文本字段上返回正确的输入)
我还尝试使用浏览器控制台并手动更改 document.getElementById("adjs1").innerHTML = "test";它将返回“test”,但该值实际上并没有改变。谁能阐明 .innerHTML 的实际作用?
最佳答案
.eq(i)返回一个 jQuery 对象,所以它没有 innerHTML 属性,所以你可以使用 .html()设置html内容
storyWords.eq(i).html(formElements.eq(i).val())
或者您可以使用 .get()这将返回一个 dom 元素引用
storyWords.get(i).innerHTML = formElements.eq(i).val();
但是你可以像这样简化整体实现
function generateMadlib() {
// Display the story. The story is initially hidden.
$("#story").css('display', "inline");
// Get the words from the textboxes.
var formElements = $("#madlibForm :text");
$("#story span").html(function (idx) {
return formElements.eq(idx).val();
})
}
关于javascript - 如何使用innertHTML,在这种情况下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667444/