jquery中的所有子选择器?

时间:2010-01-30 21:15:39

标签: jquery jquery-selectors

简化,我有以下代码:

 <a id="123" href="#"><span>click</span><span>me</span></a>

当我点击“点击”和“我”时,似乎无法使用以下jquery选择器:

 $("a").click...
也许是因为我点击了孩子们?我如何编写选择器,以便映射到'a'中的所有子项?

3 个答案:

答案 0 :(得分:5)

<强> [更新]
问题是您使用了错误的工具(即event.target属性)。这将返回事件发生的元素 on ..但不是处理事件的冒泡阶段中的元素...您需要使用event.currentTarget .. 但是在jQuery的情况下,这也与处理程序中的this关键字相同...
参考:http://api.jquery.com/event.currentTarget/

按照quirksmode的说明阅读Event order。特别注意 Use of event bubbling currentTarget

<小时/> [上一个回答]
确保在.click方法中使用函数指针或匿名函数..

所以

$("a").click( function() {/*...*/} ); // anonymous function

function some_function()
{
//...
}
$("a").click ( some_function ) // function pointer

$("a").click ( some_function() ) // unless some_function returns a function pointer..

答案 1 :(得分:2)

如果您需要获取父元素的ID,那么您只需执行此操作:

$('a').children().click(function() {
  var parentId = $(this).parent('a').attr('id');
  // Code goes here
});

答案 2 :(得分:2)

  

我必须获取父母的ID。我怎么能这样做?我目前正在使用event.target.id

$(event.target).closest('a').attr('id')会这样做。

但是没有必要使用event.target:在事件处理函数中,特殊的this变量将指向您添加处理程序的元素,而不是点击的后代元素:

$('a').click(function() {
    alert('id= '+this.id)
});

(或$(this).attr('id')如果你想迫使jQuery做一些无关紧要的工作。)

PS。不要使用以数字开头的ID。它无效,可能会混淆某些浏览器。