加载ajax html后调用jQuery函数

加载ajax html后调用jQuery函数,jquery,ajax,function,call,Jquery,Ajax,Function,Call,因此,我将这2个jQuery函数存储在一个.js文件中,.js文件在head标记之前加载 .js文件中有什么内容: $(document).ready(function(){ $("#button1").click(function(){ $.ajax({ type: 'GET', url: 'button2.php', success: function(html

因此,我将这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)
                }
            ,
        });     
    });

});
所以在身体之后我有:

<div id="button_div"><input type="button" id="button1" value="Press"></div>

按下button1时,将加载名为button2.php的php文件以及div和button2代码,但按下button2时,将不会执行button2 click函数

为什么?


如果我将button2的jQuery代码放在button2.php文件中,元素之后就可以正常工作了。但我不想那样。我希望jQuery行只保存在.js文件中,并且只保存在
标记之前。我不想在元素之后使用jQuery行。

它不起作用,因为您的选择器在第一次调用元素时不会返回它
$(“#button2”)
只调用一次,不监视DOM的更改

请改用事件委派语法:

$('#parent').on('click', '#button2', function() {
    ...
});
您的AJAX请求也可以稍微简化:

$("#button1").click(function() {
    $('#button_div').load('button2.php');
});

你能发布button1.php和button2.php的内容吗

button1.php=

<input type="button" id="button2" value="Press">

button2.php=

<input type="button" id="button1" value="Press">


在您的内部按钮1单击功能:

$("#button1").click(function(){
    $.ajax({
        type: 'GET',
        url: 'button2.php',
        success: 
            function(html){
                $("#button_div").html(html) // You forgot pass the selector as a string
            }
        ,
    });     
});
这可能会解决你的问题。另外,如果在创建元素之前调用jQuery(请记住它是自上而下的),它将不起作用。

当您调用
$(“#button2”)。单击()
#button2
还不存在,因此您不调用它。为了使单击事件工作,您需要使用事件委派(即绑定到存在的元素),如下所示:

然后,只要添加了
#按钮2
,单击它就会触发该事件回调

(我使用
document
作为示例,但尝试使用更接近
#button2
的祖先)。

这是因为创建单击处理程序时页面上不存在
#button2
。您需要使用
on()
及其对委派事件的支持来完成您想要做的事情

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

理想情况下,您可以在创建包含事件处理程序的
#button2
之前获取页面上存在的元素,而不是在第一个
$(#button_div)中的
文档

。html(html)
缺少引号
$(“#button_div”).html(html)
。另外,这两个ajax调用可以用一个按钮完成,并使用按钮id填充URL。我相信您只需要将其设置为
$(“#button2”)。在(“单击”,函数(){})对吗?@JustinChmura:不太对
.on()
不是
.live()
。使用事件委派语法,实际上是将事件处理程序绑定到父元素,然后将事件向下延伸到与第二个选择器匹配的子元素。@JustinChmura这对于在
#button2
尚不存在时要处理单击事件的情况是不正确的。必须使用本例中所示的事件委派语法。
$(document).on('click', '#button2', function() {
    $.ajax({
        type: 'GET',
        url: 'button1.php',
        success: 
            function(html){
                $('#button_div').html(html)
            }
    });     
});