Jquery How To Make $(this) Selector Fires Multiple Classes
Solution 1:
From this- Event binding on dynamically created elements?
on
function in jQuery can attach event to already created elements only directly.
For example, you can use following code for dynamically created table2
-
$('body').on('click', '.table2 a.name', function (event){
//Code here
});
When there is a click on the body
, check if target is .table2 a.name
, if yes, execute the function.
Solution 2:
I found a workaround for this post.
The problem is in jQuery the function this
on click function only refer to the element
that got clicked. It's never counted on other elements which is declared as selectors even if they have identical contents.
So the solution if you have same content in multiple elements is to use filter
function to search for same values and then you can threated them all as one in your action.
In my case I just need to marked the same a href
values in all elements.
The updated snippet
$('.table1 a.name, .table2 a.name').click(function(c){
c.preventDefault();
var $item = $(this).attr('href');
var checked = $('<img class="checked" src="https://findicons.com/files/icons/1964/colorcons_green/128/checkmark.png" width="30" height="30">');
//$.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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h2>Table 1</h2><tableclass="table1"><tr><th>Company</th><th>Contact</th><th>Country</th></tr><tr><td><aclass="name"href="https://stackoverflow.com">Alfreds Futterkiste</a></td><td>Maria Anders</td><td>Germany</td></tr><tr><td><aclass="name"href="https://stackoverflow.com/2">Centro comercial Moctezuma</a></td><td>Francisco Chang</td><td>Mexico</td></tr><tr><td><aclass="name"href="https://stackoverflow.com/3">Ernst Handel</a></td><td>Roland Mendel</td><td>Austria</td></tr></table><h2>Table 2</h2><tableclass="table2"><tr><th>Company</th><th>Contact</th><th>Country</th></tr><tr><td><aclass="name"href="https://stackoverflow.com">Alfreds Futterkiste</a></td><td>Maria Anders</td><td>Germany</td></tr><tr><td><aclass="name"href="https://stackoverflow.com/2">Centro comercial Moctezuma</a></td><td>Francisco Chang</td><td>Mexico</td></tr><tr><td><aclass="name"href="https://stackoverflow.com/3">Ernst Handel</a></td><td>Roland Mendel</td><td>Austria</td></tr></table>
Post a Comment for "Jquery How To Make $(this) Selector Fires Multiple Classes"