问题描述
我来维护一段javascript,从服务器下载一些JSON数据,建立一个新的表格行(如 $('< tr>< / tr'))并将其插入到文档中。a 节点在一点创建这样:
var a = $('< a class =foohref =#> / A>');
此后,一个事件是这样的:
a.click(function(){
// yadda yadda
return false;
});
唯一的问题是这似乎不起作用。也不会通过 on()或不推荐使用的 live()绑定。处理程序只是忽略,从不触发,页面滚动到顶部(由于 href =#)。绑定事件时,该元素已经被追加到DOM中。任何帮助将不胜感激。
出现的一些上下文信息:元素是在循环遍历数据的循环内创建的,但这不应该是一个问题除非javascript有一些真正的有趣的东西继续进行范围界定,加上所有其他的东西我尝试与元素的工作:我可以改变其内容,造型,只有事件绑定不'工作当然,jQuery版本是 1.8.3 。
.on()应该像这样设置为动态创建的元素。另外,请确保使用Jquery版本1.8(最新版本)
此外,如果您不想滚动到
以下是
var a = $('< a class =foohref =# > ASD< / A>');
a.appendTo($(body));
$('body')。on('click','a',function(e){
e.preventDefault();
$(this) ('< br />< a class =foohref =#> ASD< / a>');
});
I've come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $('<tr></tr')) and inserts it into the document.
The a node is, at one point created like this:
var a = $('<a class="foo" href="#"></a>');
and later, an event is bound to it like this:
a.click(function () { // yadda yadda return false; });
The only problem is that this doesn't seem to work. Neither does binding through on() or the deprecated live(). The handler is simply "ignored", never fires and the page scrolls to the top (due to the href="#"). When binding the event, the element is already appended to DOM. Any help would be greatly appreciated.
Some contextual information that comes to mind: the element is created inside a loop iterating over the data, but that shouldn't be a problem unless javascript has some really weird stuff going on with scoping, plus everything else I try with the element works: I can change its content, styling, only the event binding doesn't work. And of course, the jQuery version, which is 1.8.3.
EDITED
The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 (newest release)
Also, you need to prevent the standard action of the click if you don't want to scroll to the top.
Here is a working FIDDLE
var a = $('<a class="foo" href="#">ASD</a>'); a.appendTo($("body")); $('body').on('click', 'a', function(e) { e.preventDefault(); $(this).after('<br/><a class="foo" href="#">ASD</a>'); });
这篇关于jQuery - 不能将事件绑定到动态元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!