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

javascript - store HTML tag attribute value in a variable using Jquery - Stack Overflow

programmeradmin1浏览0评论

I am developing an application using JQuery. This is a fragment of the HTML code I am using:

<MarkNag class="altcheckboxoff" id="markable_38" Azpimark_id="100038">helburua </MarkNag>    
<MarkNag class="altcheckboxoff" id="markable_2"  Azpimark_id="100002">Oriolek </MarkNag>
<MarkNag class="altcheckboxoff" id="markable_39" Azpimark_id="100039">gas liberalizazioa </MarkNag>

I have the next JQuery script in the HTML page:

<script type='text/javascript'>
   $("MarkNag").click(function (){
      $(this).toggleClass("highlight");
   });
</script>

I would like to know how could I store "markable_39" in a variable if this MarkNag tag was clicked. I guess I should use .data(). But I dont really know how. Any ideas? Thanks

I am developing an application using JQuery. This is a fragment of the HTML code I am using:

<MarkNag class="altcheckboxoff" id="markable_38" Azpimark_id="100038">helburua </MarkNag>    
<MarkNag class="altcheckboxoff" id="markable_2"  Azpimark_id="100002">Oriolek </MarkNag>
<MarkNag class="altcheckboxoff" id="markable_39" Azpimark_id="100039">gas liberalizazioa </MarkNag>

I have the next JQuery script in the HTML page:

<script type='text/javascript'>
   $("MarkNag").click(function (){
      $(this).toggleClass("highlight");
   });
</script>

I would like to know how could I store "markable_39" in a variable if this MarkNag tag was clicked. I guess I should use .data(). But I dont really know how. Any ideas? Thanks

Share edited May 12, 2012 at 18:08 vol7ron 42.2k22 gold badges125 silver badges175 bronze badges asked May 12, 2012 at 18:05 HaritzHaritz 1,7527 gold badges33 silver badges50 bronze badges 2
  • possible duplicate of Getting an element's id attribute and get an element's id and probably many others... – Felix Kling Commented May 12, 2012 at 18:07
  • 1 this refers to a DOM element. You can access a DOM element's ID with this.id. – Felix Kling Commented May 12, 2012 at 18:07
Add a ment  | 

5 Answers 5

Reset to default 2

Do it like this

$("MarkNag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;
       //or
       IdOfTag = $(this).attr('id');  

 });

Also, you can just use this.id, like:

var id = this.id;

Actually, the correct code would be $(this).attr("id").

$("MarkNag").click(function (){
   $(this).toggleClass("highlight");

   alert(this.id);               // Method 1: this.id
   alert($(this).attr('id'));    // Method 2: $(this).attr('id')
});

here u will get object from where the event occurs

var eventobject = arguments.callee.caller.arguments[0];

here u can access any attribute of currentTarget (in this case id)

var id = $(eventobject.currentTarget).attr("id");
发布评论

评论列表(0)

  1. 暂无评论