开发者

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> 开发者_C百科(in a table).

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


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");
});


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");
});


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜