How to add class on click with jQuery to list item?
I have a list item like
<ul>
开发者_高级运维<li><img id="1" src="" /></li>
<li><img id="2" src="" /></li>
<li><img id="3" src="" /></li>
</ul>
<input type="button" >
I would like on click of any of the list to add class and remove from others with jQuery. Basically to make only one item selected at the time.
and on button click to show id of selected list item
This will do what you want AND get you the ID of the img
tag within the selected li
$('ul > li').click(function() {
$('ul > li').removeClass('active');
$(this).addClass('active');
});
$('input:button').click(function() {
alert($('li.active img')).attr('id'));
});
$('li').click(function() { // should be better selector than just li
$('li').removeClass('active'); // remove all active classes
$(this).addClass('active'); // add active class to element clicked
});
$('input[type="button"]').click(function() {
alert($('li.active img').attr('id')); // get active id
});
EDIT misread your code. Added the fix to get the id of the image tag.
See it working here http://jsfiddle.net/usmanhalalit/Jbh3q/1/
I have slightly changed your markup to match with the standard(just added id
) and added a red background with to show the effect in the fiddle.
Markup:
<ul id="myul">
<li><img id="1" src="" /></li>
<li><img id="2" src="" /></li>
<li><img id="3" src="" /></li>
</ul>
<input id="btn" type="button" value="click" />
JavaScript:
$(function(){
$("#myul li").click(function(){
$("#myul li").removeClass('selected');
$("#myul li").css('background','none');
$(this).css('background','red');
$(this).addClass('selected');
});
$('#btn').click(function(){
alert( $('.selected img').attr('id') );
});
});
// On li click
$("li").click(function() {
// Reset them
$("li").removeClass("yourClass");
// Add to the clicked one only
$(this).addClass("yourClass");
});
// On button click
$("input[type=\"button\"]").click(function() {
// Echo the id of selected li
alert($(".yourClass").attr("id"));
});
精彩评论