2013-08-21 119 views
0

我试图拦截该链接的点击:拦截超级链接点击

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

这个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; 
})(); 

但URL '#'负载和代码在点击()函数没有按不会跑。我错过了什么?

我在使用bootstrap的烧瓶应用程序中使用此代码。

回答

7

好像你正试图附加一个事件处理程序的元素尚不存在

(function() { 
})(); 

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

你需要的是与

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

代替

来包装你的代码