Javascript 将单击事件附加到尚未添加到 DOM 的 JQuery 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10920355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attaching click event to a JQuery object not yet added to the DOM
提问by danielrvt
I've been having a lot of trouble attaching the click event to a JQuery object before adding it to the DOM.
在将单击事件添加到 DOM 之前,我在将单击事件附加到 JQuery 对象时遇到了很多麻烦。
Basically I have this button that my function returns, then I append it to the DOM. What I want is to return the button with its own click handler. I don't want to select it from the DOM to attach the handler.
基本上我有我的函数返回的这个按钮,然后我将它附加到 DOM。我想要的是返回带有自己的点击处理程序的按钮。我不想从 DOM 中选择它来附加处理程序。
My code is this:
我的代码是这样的:
createMyButton = function(data) {
var button = $('<div id="my-button"></div>')
.css({
'display' : 'inline',
'padding' : '0px 2px 2px 0px',
'cursor' : 'pointer'
}).append($('<a>').attr({
//'href' : Share.serializeJson(data),
'target' : '_blank',
'rel' : 'nofollow'
}).append($('<image src="css/images/Facebook-icon.png">').css({
"padding-top" : "0px",
"margin-top" : "0px",
"margin-bottom" : "0px"
})));
button.click(function () {
console.log("asdfasdf");
});
return button;
}
The button that is return is unable to catch the click event. However, if I do this (after the button is added to the DOM):
返回的按钮无法捕捉点击事件。但是,如果我这样做(在将按钮添加到 DOM 之后):
$('#my-button').click(function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
It works... but not for me, not what I want.
它有效......但不适合我,不是我想要的。
It seems to be related to the fact that the object is not yet a part of the DOM.
这似乎与对象还不是 DOM 的一部分这一事实有关。
Oh! By the way, I'm working with OpenLayers, and the DOM object that I'm appending the button to is an OpenLayers.FramedCloud (Which is not yet a part of the DOM but will be once a couple of events are triggered.)
哦!顺便说一下,我正在使用 OpenLayers,我将按钮附加到的 DOM 对象是一个 OpenLayers.FramedCloud(它还不是 DOM 的一部分,但一旦触发了几个事件就会成为。)
回答by ?????
Use this. You can replace body with any parent element that exists on dom ready
用这个。您可以将 body 替换为 dom ready 上存在的任何父元素
$('body').on('click', '#my-button', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Look here http://api.jquery.com/on/for more info on how to use on() as it replaces live() as of 1.7+.
在http://api.jquery.com/on/ 上查看有关如何使用 on() 的更多信息,因为它从 1.7+ 开始替换 live()。
Below lists which version you should be using
下面列出了您应该使用的版本
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
回答by Matas Vaitkevicius
I am really surprised that no one has posted this yet
我真的很惊讶还没有人发布这个
$(document).on('click','#my-butt', function(){
console.log('document is always there');
})
If you are unsure about what elements are going to be on that page at that time just attach it to document
.
如果您不确定当时该页面上将包含哪些元素,只需将其附加到document
.
Note:this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.
注意:从性能角度来看,这是次优的 - 为了获得最大速度,应该尝试附加到将要插入的元素的最近父元素。
回答by Vins
Try this.... Replace body with parent selector
试试这个.... 用父选择器替换 body
$('body').on('click', '#my-button', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
回答by j08691
Try:
尝试:
$('body').on({
hover: function() {
console.log("yeahhhh!!! but this doesn't work for me :(");
},
click: function() {
console.log("yeahhhh!!! but this doesn't work for me :(");
}
},'#my-button');
When using .on() and binding to a dynamic element, you need to refer to an element that already exists on the page (like body in the example). If you can use a more specific element that would improve performance.
使用 .on() 并绑定到动态元素时,您需要引用页面上已存在的元素(如示例中的 body)。如果您可以使用更具体的元素来提高性能。
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
事件处理程序仅绑定到当前选定的元素;当您的代码调用 .on() 时,它们必须存在于页面上。为确保元素存在且可以被选择,请在文档就绪处理程序中为页面上 HTML 标记中的元素执行事件绑定。如果将新 HTML 注入页面,则在将新 HTML 放入页面后选择元素并附加事件处理程序。或者,使用委托事件来附加事件处理程序,如下所述。
Src: http://api.jquery.com/on/
源代码:http: //api.jquery.com/on/
回答by Marco Allori
回答by Jorge
On event
活动现场
$('#my-button').on('click', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
Or add the event after append
或者在追加后添加事件
回答by Fabien Haddadi
Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.
为那些使用 .on() 侦听绑定在最近加载的表格单元格内的输入上的事件的人补充信息;我设法通过使用 delegate() 将事件处理程序绑定到此类表格单元格,但 .on() 不起作用。
I bound the table id to .delegate() and used a selector that describes the inputs.
我将表 id 绑定到 .delegate() 并使用了一个描述输入的选择器。
e.g.
例如
HTML
HTML
<table id="#mytable">
<!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
<tr><td><input name="qty_001" /></td></tr>
<tr><td><input name="qty_002" /></td></tr>
<tr><td><input name="qty_003" /></td></tr>
</table>
jQuery
jQuery
$('#mytable').delegate('click', 'name^=["qty_"]', function() {
console.log("you clicked cell #" . $(this).attr("name"));
});
回答by PsychoDUCK
Does using .live work for you?
使用 .live 对你有用吗?
$("#my-button").live("click", function(){ alert("yay!"); });
EDIT
编辑
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
从 jQuery 1.7 开始,不推荐使用 .live() 方法。使用 .on() 附加事件处理程序。旧版本 jQuery 的用户应该优先使用 .delegate() 而不是 .live()。
回答by Nishu Tayal
jQuery .on method is used to bind events even without the presence of element on page load. Here is the linkIt is used in this way:
jQuery .on 方法用于绑定事件,即使页面加载时不存在元素。这是以 这种方式使用的链接:
$("#dataTable tbody tr").on("click", function(event){
alert($(this).text());
});
Before jquery 1.7, .live()method was used, but it is deprecated now.
在 jquery 1.7 之前,. 使用了 live()方法,但现在已弃用。
回答by ZERO
Maybe bind() would help:
也许 bind() 会有所帮助:
button.bind('click', function() {
alert('User clicked');
});