jquery单击事件,标签没有href

时间:2013-01-25 11:44:49

标签: jquery ajax

我有主页,我在其中定义ID为“mydiv”的DIV。然后我使用ajax在DIV中加载一些链接文本。

现在我想在任何人点击这些链接时做点什么,所以我在下面定义了我的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>

任何人请告诉我我做错了什么?

谢谢,

3 个答案:

答案 0 :(得分: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());
});

答案 1 :(得分: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>

答案 2 :(得分: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());
});
相关问题