【问题标题】:all children selector in jquery?jquery中的所有子选择器?
【发布时间】:2010-01-30 21:15:39
【问题描述】:

简化,我有以下代码:

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

当我点击“点击”和“我”时,它似乎不适用于以下 jquery 选择器:

 $("a").click...

也许是因为我点击了孩子们?我如何编写选择器以便映射到“a”中的所有子代?

【问题讨论】:

  • 你那里的代码应该可以工作你有指向你页面的链接吗?
  • 它应该可以工作。你可以发布代码吗? jsbin.com/ekedo3
  • 确实,它工作得很好!
  • 好的,我想我知道问题出在哪里。 'a' 有一个 id,使用 jquery,我将根据该 id 显示一些内容。但是当我单击孩子时,他们不包含该 ID。它的父 'a' 已经获得了 id。所以当我点击孩子时,我必须获取父母的身份证。我怎么能这样做?我目前也在孩子身上使用 event.target.id 但我该如何重写它,所以如果获取父母的 id? (长评论=))
  • @noname,如果您使用 this 关键字,您将获得包含您的功能的元素(在您的情况下为“a”)。所以alert( this.id ) 将显示“123”。或者,您可以使用 event.currentTarget.id 再次显示捕获事件的实际元素..

标签: jquery jquery-selectors


【解决方案1】:

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

阅读Event order,如 quirksmode 中所述。特别注意Use of event bubblingcurrentTarget


[上一个答案]
确保在 .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】:

我必须获取父母的身份证。我怎么能这样做?我目前正在使用 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。它是无效的,可能会混淆某些浏览器。

【讨论】:

    【解决方案3】:

    如果您需要获取父元素的 id,那么您只需这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-30
      • 2013-01-29
      • 2013-09-02
      • 2011-04-27
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      相关资源
      最近更新 更多