如何在单击时使用 jQuery 添加类以列出项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7491619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add class on click with jQuery to list item?
提问by Eugene
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.
我想单击任何列表来添加类并使用 jQuery 从其他列表中删除。基本上只选择一个项目。
and on button click to show id of selected list item
并在按钮上单击以显示所选列表项的 ID
回答by John Hartsock
This will do what you want AND get you the ID of the img
tag within the selected li
这将执行您想要的操作并为您提供img
所选标签的 IDli
$('ul > li').click(function() {
$('ul > li').removeClass('active');
$(this).addClass('active');
});
$('input:button').click(function() {
alert($('li.active img')).attr('id'));
});
回答by Muhammad Usman
See it workinghere http://jsfiddle.net/usmanhalalit/Jbh3q/1/
看到它在这里工作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.
我稍微更改了您的标记以匹配标准(刚刚添加id
)并添加了红色背景以显示小提琴中的效果。
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:
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') );
});
});
回答by PeeHaa
$('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
});
EDITmisread your code. Added the fix to get the id of the image tag.
编辑误读您的代码。添加了获取图像标签 ID 的修复程序。
回答by Morgan Delaney
// 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"));
});