简体   繁体   中英

how to add id to a html tag using jquery

I have more than one links with the class of video and I want to add an id attribute, When the user clicks on a link.

My code is :

   $(function () {$(".video").click(function(e){
   e.preventDefault();
   $(this).attr('id', 'selected');
   });}); 

After clicking the link, if i see the code. Firebug shows the same code without any change.

Try plain JavaScript:

this.id = "selected";

If that works, then it's a jQuery-fart. If it still doesn't work, make sure you're using Firebug correctly (I don't use it, but I know in IE I have to click a button to refresh the DOM view) and if that still doesn't seem to fix it use a class instead (or a data-* attribute)

There is nothing wrong with the code you posted so you are doing something wrong elsewhere. Here are a few general points of advice:

  • Format your code better to understand what is going on
  • Always wrap in an enclosed function that defines $ as jQuery incase it is undefined or defined as something else in the global scope
  • Apply things like "selected" as classes, not ids
  • Don't use the short hand of document ready it is not descriptive of what it is doing and not readable

eg

(function($) {

  $(document).ready(function() {

    $('.video').click(function(ev) {

      ev.preventDefault();

      //$(this).attr('id', 'selected');
      $(this).toggleClass('selected'); // This will turn the "selected" class on and off for each click

    });

  );

})(jQuery);

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