JQUERY, Returning the object that was clicked to add a Class
Given the following:
<div id="table-filters">
<ul>
<li class="active" onclick="myfunc();">blah</li>
<li onclick="myfunc();">blah</li>
<li onclick="myfunc();">blah</li>
<li onclick="myfunc();">blah</li>
</ul>
</div>
function myfunc() {
// Activate the LI clicked
$(this).addClass("active");
}
I would lik开发者_运维问答e my JQUERY to work as follows. Add class="active" to whatever LI is clicked.
Remove your onClick
calls from the HTML, and then place the following in your .js file:
$("#table-filters li").click(function(){
$(this).addClass("active").siblings("li.active").removeClass("active");
// requested in comments: how to get id of LI clicked?
var thisID = $(this).attr("id");
});
$("#table-filters li").click(function(){
$("#table-filters li.active").removeClass("active"); // remove current active
$(this).addClass("active"); // set new active
// Put more stuff here that you want to happen when clicked.
});
Adding an event listener using this method is generally considered the "good" way, adding a listener using onlick="BLAH"
is considered a bad way.
You don't need to use .click(...); instead you can do it the way you want to do it like this:
<div id="table-filters">
<ul>
<li class="active" onclick="myfunc(this);">blah</li>
<li onclick="myfunc();">blah</li>
<li onclick="myfunc();">blah</li>
<li onclick="myfunc();">blah</li>
</ul>
</div>
function myfunc(li) {
// Activate the LI clicked
$(li).addClass("active");
}
精彩评论