简体   繁体   中英

How to attach class onClick event using JavaScript?

I have a full AJAX page with elements that act like buttons with events like

onclick="$('#workcont').load('pages/mypage.html #m3-to-12');"

The elements being referenced are <li> and <tr> (in a table).

How do I attach event handlers to add the class selected on click?

You can keep the inline onclick events and can also add additional click handler on those elements using jQuery . Try this

$("li tr").click(function(){
   $(this).addClass("selected");
});

If your page is loaded via AJAX you should attach your events with live , so if you want to attach a click event you can do it this way:

$("li, tr").live('click', function() {
  $(this).addClass("selected");
});

Update

The live() method was deprecated in jQuery version 1.7, and removed in version 1.9 . Use the on() method instead.

$("li, tr").on("click",function(){
    $(this).addClass("selected");
});

Won't

 $('#workcont').load('pages/mypage.html #m3-to-12').addClass('selected');

work also?

Or are you trying to add the class to a different element?

It is a different element. If the element is loaded because of the load() use the callback parameter:

$('#workcont').load('pages/mypage.html #m3-to-12', function() { $('li').addClass('selected'); });

If you want the element to be selected as soon as it is clicked use this:

$("li, tr").click(function() {
          $("li, tr").removeClass("selected");//To Remove any previuosly selected elements
          $('#workcont').load('pages/mypage.html #m3-to-12'); 
          $(this).addClass("selected");// Select the clicked element
        });

If you want the element to be selected as soon as the AJAX page is loaded use this:

$("li, tr").click(function() {
          $("li, tr").removeClass("selected");//To Remove any previuosly selected elements
          $(this).addClass("some_temp_unique_class_name");
          $('#workcont').load('pages/mypage.html #m3-to-12', function(response, status, xhr) {
              if (status == "success") {
                var elem = $("li.some_temp_unique_class_name,tr.some_temp_unique_class_name");
                elem.removeClass("some_temp_unique_class_name").addClass("selected");// Select the clicked element
              }
            }); 
        });

Refer .load() for more details

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