在ajax html加载后调用jQuery函数

Man*_*lin 2 ajax jquery function call

所以我将这2个jQuery函数存储在.js文件中,并且.js文件在head标记之前加载

.js文件中的内容:

$(document).ready(function(){

    $("#button1").click(function(){
        $.ajax({
            type: 'GET',
            url: 'button2.php',
            success: 
                function(html){
                    $('#button_div').html(html)
                }
            ,
        });     
    });

    $("#button2").click(function(){
        $.ajax({
            type: 'GET',
            url: 'button1.php',
            success: 
                function(html){
                    $('#button_div').html(html)
                }
            ,
        });     
    });

});
Run Code Online (Sandbox Code Playgroud)

所以身体后我有:

<div id="button_div"><input type="button" id="button1" value="Press"></div>
Run Code Online (Sandbox Code Playgroud)

当按下button1时,将使用div和button2代码加载名为button2.php的php文件,但是当按下button2时将不会执行button2单击功能.

为什么?

如果我将button2的jQuery代码放在button2.php文件中,之后元素将正常工作.但我不希望这样.我想保持jQuery行只保存在.js文件中,并且仅在</head>tag 之前保存.我不想在元素之后使用jQuery行.

Exp*_*lls 7

当你打电话时$("#button2").click(),#button2它还不存在,所以你什么都不打电话.为了使click事件有效,您需要使用事件委托(即绑定到存在的元素),如下所示:

$(document).on('click', '#button2', function () {
Run Code Online (Sandbox Code Playgroud)

然后,任何时候#button2添加,单击它将触发该事件回调.

(我document以一个例子为例,但尝试使用#button2比那更接近的祖先).