【问题标题】:Link click function of parent object to redirect to href链接父对象的点击功能重定向到href
【发布时间】:2010-01-08 21:20:50
【问题描述】:

问这个问题我感觉很愚蠢,但我想不出一个干净的方法来写这个......

这是 HTML

<li>
<a class='link_parent' href='#'>Test</a>
</li>

我希望父LI的点击功能用.link_parent重定向a的href...

所以...

$('a.link_parent').each(function() {
  $(this).parent().click(function() {
    // Need to access $(this).attr('href') of the above object
    // but can't since $(this) is now the <li> object
    // help!
  });
});

【问题讨论】:

    标签: jquery object scope this


    【解决方案1】:
    $('a.link_parent').each(function() {
        var link = this;
        $(this).parent().click(function() {
            link.attr('href');
        });
    });
    

    【讨论】:

      【解决方案2】:
      $("li").click(function(){
        $("a.link_parent", this).trigger("click");
      });
      

      只是对范围的简短说明。 this 不是获取物品的唯一途径:

      $("a.link_parent").each(function(i,o){
        // 'o' will always be a reference to this anchor
        $(this).parent().click(function(e){
          // 'e.currentTarget' will be a reference to this parent
          alert(o + " " + e.currentTarget);
        });
      });
      

      【讨论】:

        【解决方案3】:

        你可以反过来做。不知道确切的JQuery写法。

        向“li”元素添加一个点击事件并获取它的第一个子元素,即“a: 元素并获取它的href。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-01
          • 2014-01-22
          • 2021-06-20
          • 1970-01-01
          • 1970-01-01
          • 2013-11-16
          相关资源
          最近更新 更多