开发者

Why this can't work - live update using jquery

开发者 https://www.devze.com 2023-01-25 11:26 出处:网络
I am writing my code like this: function updates_cb() { in a while loop to call append_message } function append_message(message)

I am writing my code like this:

function updates_cb()
{
    in a while loop to call append_message
}

function append_message(message)
{
    append the html of message into the page
    now I am using selector to add callback to newly added element
    $(jmsg).hover(function(){console.log("hover");})
}

The problem is very weird, only the la开发者_StackOverflow社区st element that added has .hover() callback setup, others don't have hover event handler setup.

Am I doing wrong? I can't manipulate the newly added element using jQuery?


I'm pretty sure you're stumbling across the most common Javascript problem ever:

for (var x = 0; x < 10; x++) {
    setTimeout(function () { alert(x); }, 1000);
}

This alerts '10' ten times. This is because the variable x in alert(x) is a live reference, not a copy, so it'll alert whatever x is at the time it needs to alert, not what x was when the timeout was set. This works because of closures. Use another anonymous function, which introduces a new variable scope, and another closure to solve this:

for (var x = 0; x < 10; x++) {
    setTimeout((function (y) {
        return function () { alert(y); }
    })(x), 1000);
}

Since your code doesn't really show anything I could base a real answer on, I hope this helps you understand the concept.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号