How to change the background color of UL 'li' on click?
如何在点击时更改UL'li'的背景颜色?
EDIT i can change li "a" but what about the entire li
编辑我可以改变li“a”,但整个李怎么样
this works:
$(".clickableUL").click(function() {
$(this).find("li a").addClass("active");
});
but find("li") does nothing. I want the LI highlighted not just the text of the link.
但发现(“li”)什么都不做。我希望LI不仅突出显示链接的文本。
2 个解决方案
#1
// javascript
$("li>a").click(function(){
$(this).parent().toggleClass("clicked");
});
/* CSS */
li { background: blue; }
li.clicked { background: red; }
You could also use display: block;
on the <a>
to make it fill the <li>
unless you want it to stay changed.
你也可以使用display:block;在上使其填充
EDIT: d'oh! just realised you could also apply the click event directly to the <li>
itself eg.
编辑:噢哦!刚刚意识到你也可以将click事件直接应用到
$("li").click(function(){
$(this).toggleClass("clicked");
});
#2
You can modify the anchor's parent (assuming the parent is the <li> element.
您可以修改锚点的父级(假设父级是
$('a').click(function(evt) {
$(evt.target).parent().css('background-color', '#fff');
});
#1
// javascript
$("li>a").click(function(){
$(this).parent().toggleClass("clicked");
});
/* CSS */
li { background: blue; }
li.clicked { background: red; }
You could also use display: block;
on the <a>
to make it fill the <li>
unless you want it to stay changed.
你也可以使用display:block;在上使其填充
EDIT: d'oh! just realised you could also apply the click event directly to the <li>
itself eg.
编辑:噢哦!刚刚意识到你也可以将click事件直接应用到
$("li").click(function(){
$(this).toggleClass("clicked");
});
#2
You can modify the anchor's parent (assuming the parent is the <li> element.
您可以修改锚点的父级(假设父级是
$('a').click(function(evt) {
$(evt.target).parent().css('background-color', '#fff');
});