简体   繁体   中英

jQuery - How to get attribute of an element when using the 'click' event

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.

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.

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

To use jQuery methods you have to wrap this with a call to jQuery.

$('.newItem').click(function () {
    alert($(this).attr('setid'));
});

refer to the code given below:

document.getElementById("element_id").addEventListener("click",function(e)
{
 console.log(e.srcElement.getAttribute("data-name"));
},false);

Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).

<a href="#" class="newItem" data-setid="28">click me</a>

Then in jQuery (v1.4.3+) you can get it like:

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/

You're on the correct path.

$(function(){

    $('.newItem').click(function () {
        alert( $(this).attr('setid') );
    })
}); 

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.

To get the page coordinates, use the pageX and pageY properties of the event object. So:

$('.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM