即使使用没有 HRF 的标签,也可以单击jQuery



我有一个主页,我在其中定义了一个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>

有人请告诉我我做错了什么?

谢谢

因为您正在动态加载DIV with id "mydiv"内的内容(通过 ajax)....在委托事件上使用

$("#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());
});

你可以这样用。演示

$(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>

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

您必须delegate the event nearest existing parent或直接document(所有其他elems的父级)。

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

或:

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

最新更新