在将新对象注入DOM后如何使用jQuery?

时间:2013-03-26 12:44:27

标签: javascript jquery dom

我正在制作句子生成器。到目前为止,它可以采用一系列单词。然后它从sentence.yourdictionary.com获取数据来判刑。我使用$("ul.example>li").first()显示来自sentence.yourdictionary.com的第一句话。然后将其放入段<p id="sents">

因此,如果您输入 yo nose 这些词,那么您的输出将是

<p id="sents"><li id="yo"><strong>Yo</strong> ' money
back a hund'd times, de preacher says!</li><li id="nose">I will no longer be caught with a
bleeding <strong>nose</strong>, heart palpatations, week long benders or hurting myself in any major way.</li></p>

当您将鼠标悬停在新列表项上时,我希望调用一个函数。

$(document).ready( function() {
    $("li").hover( function () {
        $(this).append("<span>Testing</span>");
        var id = $(this).attr("id");
        console.log(id);
    }, function () {
        $(this).find("span:last").remove();
    });
});

将新列表项注入DOM后,这不起作用。我尝试为 mousemove 添加一个事件监听器,但是当你将鼠标悬停在它上面时,“test”这个词出现了很多次!如何在注入新的列表项后实现它?

如果您想要澄清一下,这是一个小问题:http://jsfiddle.net/varhawk5/cNKyx/1/

非常感谢你。对不起,我刚刚学习javascript!

修改

要解决此问题,我使用.on()函数作为建议的注释。虽然没有“悬停”事件,所以我认为这是唯一的方法。

$("body").on("mouseenter", "li#topWord", function() {
        var word = $(this).data("word");
        var sents = sentences[word]
        $(this).html("<div class='restOfSents' data-word='" + word +"'></div>");
        for(var i=1; i<sentences[word].length; i++) {
            $(".restOfSents").append($(sentences[word][i]));
        }
    console.log(sents);
});

$("body").on("mouseleave", "li", function() {
    // Remove the new div
});

3 个答案:

答案 0 :(得分:1)

$(document).ready( function() {
$(document).on('hover','li', function () {
    $(this).append("<span>Testing</span>");
    var id = $(this).attr("id");
    console.log(id);
}, function () {
    $(this).find("span:last").remove();
});
});

答案 1 :(得分:1)

您应该使用.on()而不是.hover()

$('li').on('mouseenter', function() { ... })

此外,您不应该使用ID。请改用data-*属性。否则,当用户输入两次相同的单词时,您的代码就会中断(因为ID是唯一的)。

var id = $(this).attr('data-example');

答案 2 :(得分:1)

你是对的!原因是$(document).ready()只在页面加载时被调用。您可以在添加时为每个新元素手动添加新的事件挂钩,也可以利用jQuery的“on”功能,该功能将自动检测符合您条件的新dom元素。