jQuery如何使$(this)选择器触发多个类

我有2个具有相同包含的不同类的表。 表1显示在主要部分,第二个表显示在弹出function上。 两个表仍然在同一页面上的html。

我有一个使用2个类选择器的单击函数,我希望可以在单击时触发两个表并更改两个表包含。 但是click函数只能在一个表中工作,而不能在两个表中工作。

请注意,第二个表是以动态创建的,并不总是存在。

如何在每次单击时触发两个表,如果第二个表不存在则不返回错误。

我的代码:

$('.table1 a.name, .table2 a.name').click(function(c){ c.preventDefault(); var $item = $(this); var checked = $(''); //$.post("", {data:datas},function(data){ // some ajax result $($item).before(checked); $('img.checked').not(checked).remove(); //}); }); 
 table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } 
  

Table 1

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria

Table 2

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria

从这个 – 动态创建元素的事件绑定?

在jQuery中的函数只能直接将事件附加到已创建的元素。

例如,您可以使用以下代码动态创建table2

 $('body').on('click', '.table2 a.name', function (event){ //Code here }); 

当点击body ,检查目标是否为.table2 a.name ,如果是,则执行该function。

我找到了这篇文章的解决方法。

问题是在jQuery中this on click函数的function只是指被点击的元素。 即使它们具有相同的内容,它也从未计入被声明为选择器的其他元素。

因此,如果您在多个元素中具有相同的内容,那么解决方案是使用filter函数来搜索相同的值,然后您可以将它们全部作为操作中的一个进行威胁。

在我的情况下,我只需要在所有元素中标记相同a href值。

更新的代码段

 $('.table1 a.name, .table2 a.name').click(function(c){ c.preventDefault(); var $item = $(this).attr('href'); var checked = $(''); //$.post("", {data:datas},function(data){ // some ajax result //$($item).before(checked); var marked = $('.table1 a.name, .table2 a.name').filter(function() { $('img.checked').not(marked).remove(); return $(this).attr('href') === $item; }).before(checked); //}); }); 
 table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } 
  

Table 1

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria

Table 2

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria