【问题标题】:Get the id of the clicked link [duplicate]获取点击链接的ID [重复]
【发布时间】:2016-08-15 19:27:01
【问题描述】:

我想用 jQuery 获取点击链接的 id。 为什么这会返回 Undefined

test = function(e) {
    alert($(e).attr('id'));
    return false;
}
$('.bleu').click(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="" class="bleu" id="h12">azeaze12</a>
<a href="" class="bleu" id="h13">azeaze13</a>
<a href="" class="bleu" id="h14">azeaze14</a>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    e替换为this,e指的是event object

    alert($(this).attr('id'));
    

    甚至更好

    $('.bleu').click(function(e) {
        alert($(this).attr('id'));
        return false;
    })
    

    【讨论】:

      【解决方案2】:

      你需要使用this它指的是被点击的dom元素,点击事件处理程序中的第一个参数是event对象

      test = function(e) {
          alert($(this).attr('id'));
          return false;
      }
      $('.bleu').click(test)
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <a href="" class="bleu" id="h12">azeaze12</a>
      <a href="" class="bleu" id="h13">azeaze13</a>
      <a href="" class="bleu" id="h14">azeaze14</a>

      【讨论】:

        【解决方案3】:

        使用this,并使用.prop 作为id 或简单地使用this.id

        test = function(e) {
            alert(this.id);
            return false;
        }
        $('.bleu').click(test);
        

        如果上下文绑定在函数上,例如在 Backbone 视图上绑定事件时,您可以使用 event.currentTarget,考虑一下:

        $(el).click(function(event) {
          console.log(this) // { "my": "context" }
          console.log(event.currentTarget); // [DOMElement]
        }.bind({
          my: 'context'
        }));
        

        【讨论】:

          【解决方案4】:

          使用点击事件并使用attr获取id。试试这个:

          $(".bleu").click(function(e) { 
            alert($(this).attr("id");
          });
          

          【讨论】:

            【解决方案5】:

            使用此关键字

             <script>
             test = function(e) {
             debugger;
              alert($(this).attr('id'));
                 return false;
                }
                $('.bleu').click(test)
            
              </script>
            

            【讨论】:

              猜你喜欢
              • 2012-11-28
              • 1970-01-01
              • 1970-01-01
              • 2018-08-21
              • 1970-01-01
              • 2020-11-29
              • 2020-01-02
              • 2011-06-08
              • 1970-01-01
              相关资源
              最近更新 更多