不确定.on()方法 [英] unsure about .on() method
问题描述
我正在使用$.click()
方法触发一些事件.但是然后我需要在声明元素之前为某些HTML元素设置一些事件.让我们以这个为例:
I was using the $.click()
method for triggering some events. But then I needed to set some events for some HTML elements before the elements were declared. Let's take this as an example:
<script>
$('div.hide').click(function() {
$('div.hide').css({'display' : 'none'});
});
</script>
<div class="hide">some text</div>
缺点是,设置.click()
方法时,div.hide
元素不存在,因此未设置任何触发器.
The downside is that when setting the .click()
method, the div.hide
elements doesn't exist, so no trigger is set.
所以我转向了.on()
方法,就像这样:
So I turned to the .on()
method, like so:
<script>
$('div.hide').on('click', function() {
$('div.hide').css({'display' : 'none'});
});
</script>
<div class="hide">some text</div>
但这也不起作用.我以为调用.on()
会使所有存在的元素以及将来的div.hide
元素触发'click' function()
.
But this also doesn't work. I thought calling .on()
would make all existent and future div.hide
elements trigger the 'click' function()
.
我设法克服了这种不便,但据我所知,我想知道自己在做什么错.无法将触发器分配给将来的HTML元素吗?
I managed to get past this inconvenience, but for my own knowledge I'd like to know what was I doing wrong. Is there no way to assign a trigger to future HTML elements?
我的哀求是:
<script>
$(document).ready( function() {
$('div.hide').click(function() {
$('div.hide').css({'display' : 'none'});
});
});
</script>
<div class="hide">some text</div>
推荐答案
您错过了三参数版本:
$('body').on('click', 'div.hide', function() { ... });
这会将处理程序放置在<body>
上,但会捕获起泡的事件,并在目标元素与选择器(第二个参数)匹配时调用处理程序.
That puts the handler on the <body>
but it catches the events that bubble and invokes the handler when the target element matches the selector (the second argument).
处理程序不必继续执行<body>
;它可以是<div>
的任何父容器元素.
The handler doesn't have to go on the <body>
; it can be any parent container element of your <div>
.
"on"方法取代了较早的"live"和"delegate"方法,以及"bind"本身.
The "on" method replaces the older "live" and "delegate" methods, as well as "bind" itself.
这篇关于不确定.on()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!