无法使Jquery.closest()正常工作?
我无法让Jquery无法使Jquery.closest()正常工作?,jquery,Jquery,我无法让Jquery.nexist()正常工作 这是我的代码,它很简单,我看不出它不工作的任何原因: Jquery show:function(a,fx){ $('.more-content').hide(); $(a).toggle(function() { t = $(this).closest(".more-content") if (fx.match('show')) {
.nexist()
正常工作
这是我的代码,它很简单,我看不出它不工作的任何原因:
Jquery
show:function(a,fx){
$('.more-content').hide();
$(a).toggle(function() {
t = $(this).closest(".more-content")
if (fx.match('show')) {
t.show()
};
if (fx.match('slide')) {
t.slideDown()
};
if (fx.match('fade')) {
t.fadeIn()
};
$(this).html('Less')
}, function() {
if (fx.match('show')) {
t.hide()
};
if (fx.match('slide')) {
t.slideUp()
};
if (fx.match('fade')) {
t.fadeOut()
};
$(this).html('More')
});
}
HTML
<p><strong class="goal">The Goal</strong><br />
To support those who are NEET <span class="more-content">We do this by providing education or training to enable said people to be...</span>
<span class="more">More</span>
<br /><br />
To build community cohesion in the local area. <span class="more-content">This will lead to a community where people have the opportunity...</span>
<span class="more">More</span>
</p>
目标
为了支持那些啃老族,我们通过提供教育或培训来帮助他们成为。。。
更多
在当地建立社区凝聚力。这将导致一个社区,人们有机会。。。
更多
困惑,因此非常感谢您的帮助,谢谢如果传递到
show
方法的变量是。更多的元素,那么您需要使用选择同级元素,而不是祖先元素
var t = $(this).prev(".more-content");
另外,您正在创建一个全局变量(t
)来保存切换函数的当前元素,但这不是一个好方法。只需在两个函数中选择适当的t
元素:
var fx=‘幻灯片’
$(a).toggle(function() {
var t = $(this).prev(".more-content");
if (fx.match('show')) {
console.log('1');
t.show();
};
if (fx.match('slide')) {
console.log('2');
t.slideDown();
};
if (fx.match('fade')) {
console.log('3');
t.fadeIn();
};
$(this).html('Less')
}, function() {
var t = $(this).prev(".more-content");
if (fx.match('show')) {
t.hide()
};
if (fx.match('slide')) {
t.slideUp()
};
if (fx.match('fade')) {
t.fadeOut()
};
$(this).html('More')
});
这里有一个演示:确保jQuery语句以结尾代码>并请显示您的标记;在没有看到标记的情况下,我们无法验证您的选择器/遍历!很可能。更多内容不是锚定标记的祖先,因为如果锚定标记要可见,它必须可见<代码>.closest
仅用于选择祖先,而不是兄弟姐妹。请阅读@Mathletics上的文档。我已将HTML添加到问题中。我需要将最接近$(a)
isI的兄弟姐妹作为目标。我已经尝试过.prev()
但如果两个同时打开更多内容,则会导致冲突time@Nasir.more content
是.more
元素之前相邻的同级元素,因此使用.prev('.more content')
可以正常工作。查看此演示:@Nasir My code works,您遇到的问题是将t
变量设置为全局变量,因此在不同的事件处理程序中会混淆它。请确保在这两个函数中都使用var t=…
,它们将按照您的预期工作。。。我只需要将var t..
添加到切换fn的另一部分