获取单击的链接的 ID

Get the id of the clicked link

本文关键字:ID 链接 获取 单击      更新时间:2023-09-26

>我想用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>

e替换为this,e是指事件对象。

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

甚至更好

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

使用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>

使用 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'
}));

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

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

用户此关键字

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