如何使用innerHTML,在以下情况中

时间:2014-10-31 04:13:16

标签: javascript jquery html css innerhtml

通过让用户在文本字段中输入单词然后替换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实际上做了什么吗?

1 个答案:

答案 0 :(得分:0)

.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();
    })
}