我有不同的部门,带有隐藏/显示标签。我需要的是以下内容:如果打开一个分区,则应隐藏其他分区。这段代码使用的jQuery:jquery/1.8.2/jquery.min.js,完整代码如下:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.bhlink').on('click', function () {
$(this).text(function (i, txt) {
return txt.indexOf('MORE') != -1 ? 'HIDE' : 'MORE';
}).closest('.nn').next('.bhinfo').slideToggle();
});
});
</script>
CSS 代码:
.bhinfo { display: none; }
.nn { margin: 5px 0 5px 0; font-weight: bold;}
正文中的 HTML:
David jhon<br /><div class="nn">
<a class="bhlink" href="javascript:void(0)">MORE</a></div>
<div class="bhinfo">Mobile: 99934 59234</div>
Peter mick <br /><div class="nn">
<a class="bhlink" href="javascript:void(0)">MORE</a></div>
<div class="bhinfo">Mobile: 88934 59234</div>
Sleek boon <br /><div class="nn">
<a class="bhlink" href="javascript:void(0)">MORE</a></div>
<div class="bhinfo">Mobile: 76534 59234</div>
请帮助我,请纠正代码?
最佳答案
$(this)
将包装一个单个元素,没有必要将一个函数传递给text
,因为你知道它只会循环一个元素。
据我所知,您实际上并没有做出任何努力来显示或隐藏任何东西。
我假设单击 HIDE 链接应该隐藏其关联的 div。所以(见代码注释):
$(function() {
$('.bhlink').on('click', function () {
// Get jQuery wrappers for the link that was clicked,
// and the .bhinfo connected to it
var $this = $(this),
$bhinfo = $this.closest(".nn").next(".bhinfo");
// Are we showing or hiding?
if ($this.text() == 'MORE') {
// Showing, hide all that are visible and change
// their links' associated text to 'MORE'
$(".bhinfo:visible")
.slideUp()
.prev(".nn").find(".bhlink").text('MORE');
// Show our div and change our text
$bhinfo.slideDown();
$this.text('HIDE');
} else {
// Hiding -- just slide our div up and change our text
$bhinfo.slideUp();
$this.text('MORE');
}
});
});
.bhinfo { display: none; }
.nn { margin: 5px 0 5px 0; font-weight: bold;}
David jhon<br /><div class="nn">
<a class="bhlink" href="javascript:void(0)">MORE</a></div>
<div class="bhinfo">Mobile: 99934 59234</div>
Peter mick <br /><div class="nn">
<a class="bhlink" href="javascript:void(0)">MORE</a></div>
<div class="bhinfo">Mobile: 88934 59234</div>
Sleek boon <br /><div class="nn">
<a class="bhlink" href="javascript:void(0)">MORE</a></div>
<div class="bhinfo">Mobile: 76534 59234</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 分区隐藏在 jquery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29554980/