2012-09-02 130 views
0

我想加载框架中的链接时,我徘徊他们,但不工作。如果我在页面上创建的任何链接都使用此函数,但是当我在动态创建时使用它时不起作用。使用jquery动态创建内容

这是页面

$('#user-tweets').append('<table class="tweets" width="320" border="0"><tr><td rowspan="1">' + 
    user + '</td><td rowspan="1">' + 
    date + '</td></tr><tr><td width="45"><a href="' + 
    profile_img + '"><img src="' + 
    profile_img + '" width="55" height="50"/></a></td><td width="186">' + 
    text + '<p><a href="' + url + '"target="_blank">' + 
    url + '</a></p></td></tr></table><hr>' 
); 

上创建...和我使用这个函数打开链接到帧当我徘徊的数据。

$("a").hover(
    function() { 
    $(this).append($("<iframe src='"+this.href+"'></iframe>")); 
    }, 
    function() { 
    $(this).find("iframe:last").remove(); 
    } 
); 

回答

0

你必须使用委托的事件处理程序,使用.on()

$('#user-tweets').on('mouseenter', "a", function() { 
    $(this).append($("<iframe src='"+this.href+"'></iframe>")); 
}).on('mouseleave', 'a', function() { 
    $(this).find("iframe:last").remove(); 
}); 

这个想法是,您将处理程序绑定到某个父元素,该元素在脚本运行时已经存在。然后,在新内容上触发的事件可能会将DOM树冒泡到该父项并在那里处理。因此,您可以处理匹配特定选择器的所有元素上的事件,即使它们不存在。