嵌套脚本?

时间:2013-02-07 17:55:46

标签: javascript jquery

我有一个空div,就像这样:

<div id="my-content"></div>

然后我有一些jQuery,就像这样:

/**IGNORE THIS**/
function makeButton(){
    $('#my-content').html('<input type="button" value="Say hey" id="my-button" />');
}

到目前为止,这么好。 然后我有这个js:

$(document).ready(function(){
    makeButton();
});

工作完美,但是,当我在此之后触发此按钮时,它看起来如下,它不响应按钮ID ...

$(document).ready(function(){
    makeButton();
    $('#my-button').click(function(){
        alert('Hello!');
    });
});

我当然可以将<script>$(document).ready... blah... alert('Hello');</script>添加到makeButton函数的.html()中,但我想这不是真正的方法。

我如何告诉JS在makeButton()准备好并添加了按钮后开始听取点击次数?

编辑: 好的,那很有效。抱歉。实际情况并不像上面那样,但类似。

makeButton()实际上是另一个通过ajax获取数据的函数,因此makeButton更像是这样:

makeButton(){
    $.ajax({
        type: 'POST',
        url: 'ajax_images.php',
        data: {pageNr: pageNr},
        success:function(response) {
            //Loops the json and does something like this:
            var HTML = '<div id="thumbnail">;
            HTML += 'Response Stuff'
            HTML += '</div>';
            $('#my-content').html(HTML);
        } 
    });
}

抱歉让人感到困惑。

2 个答案:

答案 0 :(得分:3)

只需做一个简单的改变:

$(document).ready(function(){
    makeButton();
    $('#my-content').on('click', '#my-button', function(){
        alert('Hello!');
    });
});

在页面加载后,您需要#my-button的委托事件作为它来到DOM树。要了解有关 jQuery 中委托事件绑定的更多信息,请参阅here

答案 1 :(得分:3)

问题是您在元素存在之前尝试绑定事件处理程序。 Ajax调用是异步的!

您可以从$.ajax电话中返回承诺对象:

function makeButton(){
    return $.ajax({
        // ...
    });
}

然后在Ajax调用成功时通过添加回调来绑定事件处理程序:

makeButton().done(function() {
    $('#my-button').click(function(){
        alert('Hello!');
    });
});

或者,您可以将事件委派用作thecodeparadox shows in his answer。要了解有关Ajax如何工作的更多信息,请查看this answer