0

次のようなコードがあります。

<div id="content">
    <div id="child1"></div>
    <div id="child2"></div>
</div>

jQueryクリックイベントを使用しています

$('#child1').click(function(){
var page = "value1";

    $('#content').hide();
    $('#content').load('includes/'+ page +'.php', function () {
        $('#content').fadeIn(speed);
    });
    return false;
});

ただし、読み込まれた #content ID のいずれかのコンテンツをクリックすると、div の子は親 ID を返します。親を無視して子 ID を選択するにはどうすればよいですか?

実際の HTML はもっと複雑なので、ページ上の子の値は単純に #content#child1 ではありません。JS に #content を無視させて #child1 を表示させる方法はありますか?

次のようなコードを使用する場合

$('div').click(function(){
    alert($(this).attr("id"));
    return false;
});

「#child1」または「#content」をクリックしたときに返される値。

4

1 に答える 1

1

I may be reading this wrong, but you've completely overwritten the the contents of #content. The #child1 and #child2 divs no longer exist once the load command has completed.

Even if your loaded data includes a #child1 div, it is not the same DOM node that you originally attached the click event to. That old node is gone, replaced by your loaded data, and the event handlers are gone too.

If you want to keep listening to #child1.click() events after the old child nodes are deleted, you have two options:

  • Re-bind events after the load completes
  • Use event delegation on the #content node

Event delegation allows you to bind a listener on #content that will fire when events bubble up from the child elements:

$('#content').on('click', '#child1', function(evt) {
    // event handler here
    // this points to the element clicked ('#child1')
});

This will effectively keep your #child1 click handler alive even after you have replaced the nodes with totally new HTML.

于 2012-10-31T20:18:44.977 に答える