我有这个代码来切换幻灯片中UL的内容:
jQuery(document).ready(function () {
jQuery("ul.item-options").click(function (evt) {
if(evt.target.tagName != 'UL')
return;
jQuery("li", this).slideToggle(500);
});
});.item-options li {
display: none;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='item-options'>
show
<li>list item</li>
</ul>
<ul class='item-options'>
show
<li>list item</li>
</ul>
<ul class='item-options'>
show
<li>list item</li>
</ul>
我想更新这个,这样“show”这个词就可以在show/hide之间切换了。
有什么想法吗?
发布于 2019-10-23 18:34:40
您可以尝试以下代码-在UL中获取html,然后根据当前值替换文本,并将html放回原处
jQuery(document).ready(function () {
jQuery("ul.item-options").click(function (evt) {
if(evt.target.tagName != 'UL')
return;
var html = jQuery(this).html();
if(html.indexOf('show')>=0) {
jQuery(this).html(html.replace('show','hide'));
} else {
jQuery(this).html(html.replace('hide','show'));
}
jQuery("li", this).slideToggle(500);
});
});.item-options li {
display: none;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<ul class='item-options'>
show
<li>list item</li>
</ul>
发布于 2019-10-23 18:35:42
首先,请注意您的HTML是无效的。不能将文本节点作为ul的子节点。要解决这个问题,可以将ul之外的show文本移入到它自己的元素中。我在下面的示例中使用了p,但任何其他的都可以。
在那里,您可以将一个click事件处理程序附加到该元素,该处理程序在相关的li元素上调用slideToggle(),然后根据单击的元素的当前设置更新其text()。试试这个:
jQuery(function($) {
$(".toggle").on('click', function() {
$('ul li').stop().slideToggle(500);
$(this).text((i, t) => t == 'show' ? 'hide' : 'show');
});
});.item-options li {
display: none;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="toggle">show</p>
<ul class="item-options">
<li>list item</li>
</ul>
还要注意,如果连续快速单击元素,则使用stop()来防止slideToggle动画排队。
https://stackoverflow.com/questions/58520806
复制相似问题