5

我正在使用$.click()触发某些事件的方法。但是我需要在元素被声明之前为一些 HTML 元素设置一些事件。让我们以此为例:

<script>
    $('div.hide').click(function() {
        $('div.hide').css({'display' : 'none'});
     });
</script>
<div class="hide">some text</div>

缺点是设置.click()方法时,div.hide元素不存在,所以没有设置触发器。

所以我转向了这个.on()方法,就像这样:

<script>
    $('div.hide').on('click', function() {
        $('div.hide').css({'display' : 'none'});
    });
</script>
<div class="hide">some text</div>

但这也行不通。我认为调用.on()会使所有现有和未来div.hide的元素触发'click' function().

我设法克服了这种不便,但就我自己的知识而言,我想知道我做错了什么。有没有办法为未来的 HTML 元素分配触发器?

我的解决办法是:

<script>
    $(document).ready( function() {
        $('div.hide').click(function() {
            $('div.hide').css({'display' : 'none'});
        });
    });
</script>
<div class="hide">some text</div>
4

2 回答 2

10

您错过了三参数版本:

$('body').on('click', 'div.hide', function() { ... });

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).

The handler doesn't have to go on the <body>; it can be any parent container element of your <div>.

The "on" method replaces the older "live" and "delegate" methods, as well as "bind" itself.

于 2012-06-11T15:35:57.653 回答
-2

Use jQuery.live method to attach an event handler for all elements which match the current selector, now and in the future

于 2012-06-11T15:53:31.840 回答