2013-08-07 45 views
1

在我的项目,我追加几个按钮,一个div:jQuery的。对(“点击”) - 替代.live()

$(".tab-content").append("<div class='landing_content'><button class='off-screen-nav-button btn btn-info btn_edit' data-effeckt='effeckt-off-screen-nav-right-overlay'>Edit</button></div>"); 

,然后监听用下面的代码点击:

$(".tab-content").on("click",".btn-edit",function(){ 
    console.log('edit'); 
}); 

为什么这不起作用?我习惯使用.live(),但它已被弃用。

谢谢。

+0

当你是绑定处理程序时,“.tab-content”元素必须位于DOM中。并修复你的选择器或类名称 –

+0

'btn_edit'和'landing_content'对于class/id名称是无效的,因为下划线不是有效/支持的(除了在某些I.E.版本中奇怪的) –

回答

7

在你的标记中你有btn_edit,在你的jQuery中你有btn-edit

更改您的标记class到jQuery选择匹配,就像这样:

$(".tab-content").append("<div class='landing_content'><button class='off-screen-nav-button btn btn-info btn-edit' data-effeckt='effeckt-off-screen-nav-right-overlay'>Edit</button></div>"); 
+1

Hahaha:D对不起。总是很高兴得到一个新的眼睛。有时你可能会迷失在所有的代码中。 –

+0

@CasperSlynge - 不用担心,有时你越盯着你自己的代码越是看起来正确,而且更难以确定它为什么会被破坏。这是StackOverflow的用途。 :-) –

3

的原因,你的方法没有工作(除了什么指出约btn-edit),可能是因为你试图绑定到实际上并没有在DOM存在,直到它被追加后的元素的事件,曾经有LIVE已经贬值了,但你可以做到这一点,而不是:

//bind the event to the document which always exists and specify the selector 
//as the second argument 
$(document).on("click",".tab-content .btn-edit",function(){ 
    console.log('edit'); 
}); 

希望这有助于见文献展jQueries如需更多帮助,请拨打here

+0

@CasperSlynge你对此有何遗憾? :S –

+0

这是为了上面的答案。 –