Javascript jQuery - 如何在使用“点击”事件时获取元素的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7519423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - How to get attribute of an element when using the 'click' event
提问by Roman
I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.
我正在使用 jQuery 来点击“a”元素。我有这些链接的列表,其中每个链接都有一个类,我正在捕获点击。
I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.
我想知道哪个链接被点击了(每个链接我都有一个属性“setid”),并且还想知道鼠标被点击的点。
How could this be accomplished?
这怎么可能实现?
example of the code:
代码示例:
<a href="#" class="newItem" setid="28">click me</a>
$('.newItem').click(function (e) {
alert(e.attr('setid'));
});
EDIT: OK, so to get the position I would use e.pageX
编辑:好的,所以为了得到我会使用 e.pageX 的位置
回答by BNL
To use jQuery methods you have to wrap thiswith a call to jQuery.
要使用 jQuery 方法,您必须通过调用 jQuery来包装它。
$('.newItem').click(function () {
alert($(this).attr('setid'));
});
回答by Roman
refer to the code given below:
参考下面给出的代码:
document.getElementById("element_id").addEventListener("click",function(e)
{
console.log(e.srcElement.getAttribute("data-name"));
},false);
回答by mikato
Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).
就像 Skylar 在对您的问题的评论中所说的那样,您可以在新属性(HTML5 有效)前使用“data-”。
<a href="#" class="newItem" data-setid="28">click me</a>
Then in jQuery (v1.4.3+) you can get it like:
然后在 jQuery (v1.4.3+) 中你可以得到它:
var setid = $(this).data("foo");
It's even a little nicer than attr() that other people have mentioned. See this for more examples - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/
它甚至比其他人提到的 attr() 更好一点。有关更多示例,请参阅此内容 - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/
回答by aziz punjani
You're on the correct path.
你走在正确的道路上。
$(function(){
$('.newItem').click(function () {
alert( $(this).attr('setid') );
})
});
回答by lonesomeday
Your code is almost right to get the attribute. The only thing missing is wrapping this
(a DOM element) in the jQuery wrapper so you can use jQuery functions. $(this).attr('setid')
should work.
您的代码几乎可以正确获取该属性。唯一缺少的是this
在 jQuery 包装器中包装(一个 DOM 元素),以便您可以使用 jQuery 函数。$(this).attr('setid')
应该管用。
To get the page coordinates, use the pageX
and pageY
properties of the event object. So:
要获取页面坐标,请使用事件对象的pageX
和pageY
属性。所以:
$('.newItem').click(function (e) { // e is the event object
alert($(this).attr('setid'));
alert(e.pageX);
alert(e.pageY);
});
See the documentation on the Event object.
请参阅有关Event 对象的文档。