2

所以我将这 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 的单击功能。

为什么?

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

4

5 回答 5

7

当你调用$("#button2").click(),#button2还不存在,所以你什么都没有调用它。为了使点击事件起作用,您需要像这样使用事件委托(即绑定到存在的元素):

$(document).on('click', '#button2', function () {

然后,任何时间#button2都被添加,单击它会触发该事件回调。

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

于 2013-01-31T23:46:01.883 回答
3

它不起作用,因为您的选择器在您第一次调用它时不会返回元素。$('#button2')只调用一次并且不监视 DOM 的变化。

改用事件委托语法:

$('#parent').on('click', '#button2', function() {
    ...
});

您的 AJAX 请求也可以简化一点:

$("#button1").click(function() {
    $('#button_div').load('button2.php');
});
于 2013-01-31T23:44:56.317 回答
0

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

button1.php=

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

button2.php=

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

?

于 2013-01-31T23:45:28.500 回答
0

在你里面 button1 点击功能:

$("#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(记住它是自上而下的),它将不起作用。

于 2013-01-31T23:45:43.397 回答
0

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

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

理想情况下,您可以在创建#button2包含#button2您可以将事件处理程序附加到而不是document.

于 2013-01-31T23:46:50.477 回答