javascript 单击更改样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15811214/
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
Change style onclick
提问by Ahmad Tantori
I want to change a tag's style using class onclick (basically I want to change the class). This is my HTML code:
我想使用类 onclick 更改标签的样式(基本上我想更改类)。这是我的 HTML 代码:
<div class="menutext"><a href="#" onclick="javascript:removeClass('menutext').addClass('menutext2');" class="scroll">Feedback</a></div>
I don't know what's wrong, why it's not working! Also I would like to make this code using JQUERY, if not possible with javascript.
我不知道出了什么问题,为什么它不起作用!另外,如果不能使用 javascript,我想使用 JQUERY 制作此代码。
回答by bipen
calling click event is better that inline javascript... readable and easy to debug...
调用 click 事件比内联 javascript 更好......可读且易于调试......
try this
试试这个
html
html
<div class="menutext"><a href="#" class="scroll">Feedback</a></div>
jquery
查询
$('.menutext a').click(function(e){
e.preventDefault(); //to prevent the default behaviour of <a>
$(this).parent().removeClass('menutext').addClass('menutext2');
//parent() because i think you want to change the class of the div ...
});
回答by chris.ribal
You didn't write a jquery selector in your onclick-event.
您没有在 onclick 事件中编写 jquery 选择器。
<div class="menutext">
<a href="#" onclick="javascript:$(this).removeClass('menutext').addClass('menutext2');" class="scroll">Feedback</a>
</div>
回答by jgillich
回答by John
As what I have understand on your question, this is what you want. jquery
正如我对你的问题的理解,这就是你想要的。查询
$('.childDiv').click(function(){
$(this).parent().find('.childDiv').css('background-color','#ffffff');
$(this).css('background-color','#ff0000');
});
html
html
Group 1
<div id="child1" class="childDiv">
Child 1
</div>
<div id="child2" class="childDiv">
Child 2
</div>
</div>
<div id="divParent2" class="parentDiv">
Group 2
<div id="child1" class="childDiv">
Child 1
</div>
<div id="child2" class="childDiv">
Child 2
</div>
</div>
CSS
CSS
.parentDiv{
border:1px solid black;
padding:10px;
width: 80px;
margin:5px;
display:relative;
}
.childDiv{
border:1px solid blue;
height: 50px;
margin:10px;
}
回答by pala?н
Try this using jQuery
and remove the onclick
attribute in link also:
尝试使用jQuery
并删除onclick
链接中的属性:
$('div.menutext > a').click(function(){
$(this).parent().removeClass('menutext').addClass('menutext2');
});