jQuery 添加和删除类到一个 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16367059/
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
add and remove class to an id
提问by the_martux
When I click on the class show the 'id does not return the class hide Can you help me? Thanks
当我点击班级显示时,'id 不返回班级隐藏你能帮我吗?谢谢
CSS
CSS
.hide{color: red}
.show{ color: green}
HTML
HTML
<div id="prova" class="hide">
prova
</div>
jQuery
jQuery
$(document).ready(function()
{
$("#prova.hide").click(function()
{
$(this).removeClass();
$(this).addClass("show")
})
$("#prova.show").click(function()
{
$(this).removeClass();
$(this).addClass("hide")
})
})
回答by pala?н
回答by Schleis
Your click events are not bound when you change the class. So when you change the class, the elements do not have events associated with them anymore.
当您更改类时,您的点击事件不受约束。因此,当您更改类时,元素不再具有与其关联的事件。
$(document).on('click', "#prova.hide", function()
{
$(this).removeClass();
$(this).addClass("show")
})
$(document).on('click', "#prova.show", function()
{
$(this).removeClass();
$(this).addClass("hide")
})
回答by James Montagne
When $("#prova.hide").click(
is called, the click
function is only applied to those elements which match the selector at the time the code is run.You should instead do something like this:
当$("#prova.hide").click(
被调用时,该click
函数仅应用于那些在代码运行时与选择器匹配的元素。你应该做这样的事情:
$("#prova").click(function()
{
var $this = $(this);
if($this.hasClass("show")){
$this.removeClass("show");
.addClass("hide");
} else {
$this.removeClass("hide");
.addClass("show");
}
});