与addClass配对时,JQuery removeClass无法正常工作

时间:2017-05-25 10:40:13

标签: javascript jquery html

我有一个按钮和一些文字。当我单击按钮时,我希望隐藏文本并显示不同的文本行:

<button type="button" id=button>Click Me!</button>

<div id="a">
This is a line of text

<div id ="b" class="hidden">
This is also a line of text  

Jquery的:

$( "#button" ).click(function() {
     $('#b').removeClass('hidden');
     $('#a').addClass('hidden');    
});

但是它只隐藏了原始文本行,并且没有显示第二行。但是,当我这样做时:

$( "#button" ).click(function() {
     $('#b').removeClass('hidden');
     // $('#a').addClass('hidden');
    });

显示两行文字。只有当我将两条线加在一起时才会出现问题。

3 个答案:

答案 0 :(得分:2)

您尚未正确关闭div

$( "#button" ).click(function() {
     $('#b').removeClass('hidden');
     $('#a').addClass('hidden');    
});
.hidden {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id=button>Click Me!</button>   
<div id="a">
This is a line of text
</div>

<div id ="b" class="hidden">
This is also a line of text
</div>

答案 1 :(得分:0)

你可以直接使用jQuery hide和show methods

$('#b').hide();
$( "#button" ).click(function() {
     $('#b').show();
     $('#a').hide();    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id=button>Click Me!</button>   
<div id="a">
This is a line of text
</div>

<div id ="b" >
This is also a line of text
</div>

答案 2 :(得分:0)

您错过了关闭div标签。

$("#button" ).click(function() {
     $('#b').removeClass('hidden');
     $('#a').addClass('hidden');    
});
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<button type="button" id=button>Click Me!</button>
<div id="a">
  This is a line of text
</div>
<div id="b" class="hidden">
  This is also a line of text 
</div>