我是jQuery的新手,我试图在不使用jQuery的切换函数的情况下创建一个show/hide切换按钮,但我不知道下面的代码有什么问题。
“隐藏”按钮可成功隐藏段落。隐藏部分起作用了。它添加了一个类“show”,删除了类“hide”,并更改了按钮的文本。我使用Dev工具来查看这个部分,这个部分正在工作,但是再次点击按钮就不工作了,即show部分。
null
$(document).ready(function() {
$(".hide").click(function() {
$(".content").hide();
$(this).addClass("show");
$(this).removeClass("hide");
$(this).text("Show");
});
$(".show").click(function() {
$(".content").show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="hide">Hide</button>
null
您可以使用toggle()
使用单个按钮轻松切换元素的可见状态。然后您可以向text()
提供一个函数,根据按钮的当前值设置按钮上的文本。试试看:
null
$(document).ready(function() {
$(".toggle").click(function() {
$(".content").toggle();
$(this).text(function(i, t) {
return t == 'Show' ? 'Hide' : 'Show';
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="toggle">Hide</button>
您不想更改类--如果您想更改,则需要委托,以便将事件注册到一个静态容器,如document
$(document).on("click",".hide",function() {
我建议改为切换:
null
$(document).ready(function() {
$(".but").on("click",function() {
$(".content").toggle();
$(this).text($(this).text()=="Show"?"Hide":"Show");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="but">Hide</button>