3

I need to access to the custom attribute or data of my link but I can't. My code is simple yet in repeater. I don't know if this is causing a problem. Here is the code:

 <a class="showAllComm" data-userid='<%# DataBinder.Eval(Container.DataItem, "USER_ID")%>' href="#sa">Show all comments</a>

Here is my click event:

$('.showAllComm').click(function(index, element) {
            var commId = $(element).data("userid");
 })

commId is undefined but I can see it in the source code that it has value of 1.

how can I access to the userId?

Thank you

2 Answers 2

8

Reference the element with this instead of the second parameter:

var commId = $(this).data("userid");

The arguments passed to an event handler are not the index and element as you'd have in .each().

By default, you just get a single event argument passed.

DEMO: http://jsfiddle.net/Jjbwd/

$('.showAllComm').click(function( event ) {

    alert( event.type ) // click

    var commId = $(this).data("userid");
});
Sign up to request clarification or add additional context in comments.

6 Comments

thank you but I wonder.. what is the reason for not being able to access with element?
@Pabuc because there is no second parameter to the callback, the only parameter is a jQuery event object.
In these cases there's no need to create the jQuery object, a simpler $.data(this, "userid") would be more efficient...as it just does a this[$.expando] call, rather than a full jQuery() call/init.
@Pabuc: Because jQuery doesn't pass a second argument by default.
@Nick: Are you sure that works to initially access data- attributes that are not yet in jQuery.cache? It doesn't seem that way in this example.
|
1

The data method is not a shortcut for the attr method. It takes an element and an attribute, per the docs

Just use attr("data-userid")

1 Comment

Well I'll be. Maybe if I'd been using this all along I wouldn't have gotten lazy about using a data prefix on all my data attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.