获取单击的链接的 ID
Get the id of the clicked link
>我想用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>
相关文章:
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 如何进行AJAX调用,使其仅在我单击包含在特定类中的链接时触发;id”;父元素的
- 通过单击链接(兄弟姐妹?)从无线电输入中获取id
- 通过id查找元素并附加链接
- url中没有id的内部链接
- 如何绑定多个具有相同敲除功能、传递不同ID的链接
- 修复Javascript代码以将文本中的所有Youtube链接转换为Youtube ID功能
- 如何从链接中检索 ID
- 检测单击的链接的 ID 以更改链接的去向
- 获取单击的链接的 ID
- 在没有 jquery 的情况下更改子节点(父节点具有 ID)中的链接文本
- 使用animate将标签链接锚定到不同页面上的ID
- 如何设置从数据库到php会话的id点击链接
- VBA IE单击/显示没有id或标记而不是超链接的javascript
- Meteor发布中通过id链接用户
- 更改切换 ID 链接的颜色
- 铬错误或编码错误?目标页面中的锚/ID 链接不起作用
- 如何控制页面上的#id链接
- 想在其他html页面上只运行匹配id链接吗
- 使 id 链接可见 - 防止单击定位点时发生默认事件