0

I'm trying to intercept clicks on this link:

<a id="test-button" href="#">Test</a>

with this js:

(function() {
    $('#test-button').click(function (event) {
        console.log("This code never gets called.")
        event.preventDefault();
        $('#alert-placeholder').html(['<div class="alert"><a class="close"',
                                      'data-dismiss="alert">×</a>',
                                      '<span>"+message+"</span></div>'].join())
        return false;
    })
    console.log("yes, this code loads");
    debugger;
})();

but the URL '#' loads and the code in the click() function doesn't run. What am I missing?

I'm using this code in a flask app using bootstrap.

4

1 回答 1

7

好像您正在尝试将事件处理程序附加到尚不存在的元素

(function() {
})();

只创建一个本地范围但不保证 DOM 加载。要确认它 - 添加console.log($('#test-button').length);到您的代码中。

你需要的是包装你的代码

$(function() {
    // your code is here
});

反而

于 2013-08-21T03:20:05.633 回答