最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get attr of jQuery html object passed with 'this' keyword - Stack Overflow

programmeradmin1浏览0评论

JQuery/JS newbie here - but so far enjoying the learning experience.

My scenario:

I have multiple buttons like so:

<button id="thumb-1" class="thumbs">click 1</button>
<button id="thumb-2" class="thumbs">click 2</button>
<button id="thumb-3" class="thumbs">click 3</button>

When a user clicks one, I pass it to a custom function via the this keyword like so:

$('.thumbs').click(function(){
    $.fn.myFunc(this);
}

Which will send the jQuery object to the function, i.e the entire button html.

<button id="thumb-x" class="thumbs">click x</button>

Now what I want to do is grab the id of that button and store it on a string variable. Using the following doesn't work of course a html button element has no attr method.

$.fn.myFunc = function(button) { 
    var id = button.attr('id');
}

Anybody have any simple ideas?

Thanks! - James

JQuery/JS newbie here - but so far enjoying the learning experience.

My scenario:

I have multiple buttons like so:

<button id="thumb-1" class="thumbs">click 1</button>
<button id="thumb-2" class="thumbs">click 2</button>
<button id="thumb-3" class="thumbs">click 3</button>

When a user clicks one, I pass it to a custom function via the this keyword like so:

$('.thumbs').click(function(){
    $.fn.myFunc(this);
}

Which will send the jQuery object to the function, i.e the entire button html.

<button id="thumb-x" class="thumbs">click x</button>

Now what I want to do is grab the id of that button and store it on a string variable. Using the following doesn't work of course a html button element has no attr method.

$.fn.myFunc = function(button) { 
    var id = button.attr('id');
}

Anybody have any simple ideas?

Thanks! - James

Share Improve this question asked Dec 5, 2012 at 10:32 user896237user896237
Add a ment  | 

3 Answers 3

Reset to default 4

If you want to use attr() then convert button to jquery object or if you want to get id from javascript object then use button.id

$.fn.myFunc = function(button) { 

    var id = $(button).attr('id'); // with jquery object
    id = button.id; //with javascript object 
}

You need to make it a jQuery object before using jQuery function

$.fn.myFunc = function(button) { 
    var id = $(button).attr('id');
}

if you send "this" from myFunc there is no need to use jquery attr we can access straightly which will be more faster and easier

$(".thumbs").click(function(){
$.fn.myFunc(this);
});
$.fn.myFunc = function(button) {
alert(button.id);
}

Refer the below fiddle

http://jsfiddle/m2Ts5/18/

Thanks

发布评论

评论列表(0)

  1. 暂无评论