简体   繁体   English

如何使用JavaScript附加class onClick事件?

[英]How to attach class onClick event using JavaScript?

I have a full AJAX page with elements that act like buttons with events like 我有一个完整的AJAX页面,其中的元素像按钮一样具有事件

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

The elements being referenced are <li> and <tr> (in a table). 被引用的元素是<li><tr> (在表中)。

How do I attach event handlers to add the class selected on click? 如何附加事件处理程序以添加单击时selected的类?

You can keep the inline onclick events and can also add additional click handler on those elements using jQuery . 您可以保留内联onclick事件,也可以使用jQuery在这些元素上添加其他click处理程序。 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: 如果您的页面是通过AJAX加载的,则应将事件附加在live上 ,因此,如果要附加click事件,可以按以下方式进行:

$("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 . live()方法在jQuery 1.7版中已弃用,在1.9版中已删除。 Use the on() method instead. 请改用on()方法。

$("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: 如果由于load()而加载了元素,请使用callback参数:

$('#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: 如果要在加载AJAX页面后立即选择元素,请使用以下命令:

$("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 有关更多详细信息,请参考.load()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM