事件处理程序和jquery .load()

时间:2014-03-15 18:27:18

标签: jquery ajax events

我在点击后使用ajax插入其他内容。 在内容中,我想对另一个点击事件做出反应。 但不幸的是它没有用 - 警报()没有被解雇。

的test.html

<button id="button_load">load text</button>
<div id="content"><!--content--></div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$("#button_load").on("click", function(){ $("#content").load("test_content.html"); });
$("#button_hide").on("click", function(){ alert("hide text"); });
</script>

test_content.html

<p>Lorem ipsum</p>
<button id="button_hide">hide text</button>

知道问题可能是什么或如何修复它?

2 个答案:

答案 0 :(得分:4)

.on('click')的赋值在运行时发生,当它分配的HTML尚不存在时。你可以做以下两件事之一:

加载后分配回调函数

$('#button_load').on('click',function(){
    $('#content').load('test_content.html',function(){
        $('#button_hide').on('click',function(){
            alert('hide text');
        });
    });
});

委派您的点击处理程序

$('#button_load').on('click',function(){
    $('#content').load('test_content.html');
});

$('#content').on('click','#button_hide',function(){
    alert('hide text');
});

委托通常是首选,因为它对DOM的影响较小且可重用,但取决于您。如果你朝那个方向发展,我会利用缓存:

var $content = $('#content');

$('#button_load').on('click',function(){
    $content.load('test_content.html');
});

$content.on('click','#button_hide',function(){
    alert('hide text');
});

这样您只需查询一次DOM。

答案 1 :(得分:1)

尝试更改此行:

$("#button_hide").on("click", function(){ alert("hide text"); });

到这一行:

$("#content").on("click", "#button_hide", function(){ alert("hide text"); });
相关问题