2013-01-25 63 views
0

我有我定义一个ID为“mydiv”的DIV的主页。然后我使用ajax加载该DIV中的一些链接文本。jquery点击甚至没有href

现在我想做点什么,当有人点击这些链接时,所以我定义了我的jquery,如下所示。

$("#mydiv > a").live('click',function(){ 
    alert($(this).text()); 
}); 

加载的内容都在下面的表格

<a style="cursor:pointer;">Text 1</a> 
<a style="cursor:pointer;">Text 2</a> 
<a style="cursor:pointer;">Text 3</a> 

有谁请告诉我,我做错了什么?

感谢,

+1

您正在使用哪个版本的jQuery?即使“live”已被弃用(并且在1.9.0版本中被删除),它仍然可以在1.8及更高版本上正常工作。 – fcalderan

+0

在这里很好用http://jsfiddle.net/8EzKG/使用jQuery 1.8。 ''标签是否指导'mydiv'的孩子? – charlietfl

+0

我正在使用jquery 1.8.3 ... – abdfahim

回答

3

,因为你是动态加载内DIV with id "mydiv"含量(AJAX)....使用on委托事件

$("#mydiv").on('click','a',function(e){ 
    e.preventDefault(); //you may not need this... but this stops the default behaviour of <a> tag 
    alert($(this).text()); 
}); 
+0

这是工作!奇怪的是,我使用1.8.3所以生活应该工作以及...无论如何,谢谢... – abdfahim

+0

欢迎@ AbdullahFahim..happy编码... – bipen

1

你可以用这样的。 Demo

$(document).ready(function(){ 

$("a").on('click',function(){ 
    alert($(this).text()); 
}); 

}); 

HTML

<a style="cursor:pointer;">Text 1</a> 
<a style="cursor:pointer;">Text 2</a> 
<a style="cursor:pointer;">Text 3</a> 
+0

这种使用'on'将不会委托处理程序为' '标签并且不是'live'的替代品,因为 – charlietfl

1

当您正在加载您的内容动态.on()处理程序将在jQuery的版本1.9.0用于此:

你必须delegate the eventnearest existing parent或直接输入document(这是所有其他元素的父项)。

$("#mydiv").on('click','a', function(){ 
    alert($(this).text()); 
}); 

或:

$(document).on('click','#mydiv a', function(){ 
    alert($(this).text()); 
}); 
+0

'on'比jQuery 1.9 – charlietfl

+0

更远,如果使用jQuery 1.9.0版。 – Jai