当单击类read-more时,我有一个按钮设置为切换div的高度,但是在每个页面上都有多个版本的相同代码,因为文章是通过wp_query生成的。如何调整下面的代码,使其只切换与代码块相同的读更多的div?
<article>
<h3>Title</h3>
<p>Intro text</p>
<div class="read-more">
<p>Toggle Text</p>
</div>
<button class="toggle-text">Read More</button>
</article>
<article>
<h3>Title</h3>
<p>Intro text</p>
<div class="read-more">
<p>Toggle Text</p>
</div>
<button class="toggle-text">Read More</button>
</article>JS
/* Toggle event to show/hide 'read more' content */
$(document).ready(function(){
$("button.toggle-text").click(function(){
$(".read-more").animate({
height: "toggle",
opacity: "toggle"
}, 400);
});
});
$(function(){
$(".toggle-text").click(function () {
$(this).text(function(i, text){
return text === "Read More" ? "Read Less" : "Read More";
})
});
})发布于 2015-11-26 14:13:14
改变这一点:
$(".read-more").animate({对此:
$(this).siblings(".read-more").animate({上面的代码查找具有相同父类下的read-more类的元素。
发布于 2015-11-26 14:11:20
.read-more是前一个单击按钮的同级。您可以通过单击按钮上下文this和按钮单击处理程序中的.prev()来锁定它。或者您可以遍历最近的文章元素,然后在其中找到.read-more。此外,您也不需要分离处理程序来实现这一点。您可以用单击处理程序编写代码。
$(".toggle-text").click(function () {
$(this).prev(".read-more").animate({
height: "toggle",
opacity: "toggle"
}, 400);
$(this).text(function(i, text){
return text === "Read More" ? "Read Less" : "Read More";
})
});或:
$(".toggle-text").click(function () {
$(this).closest('article').find(".read-more").animate({ //or
height: "toggle",
opacity: "toggle"
}, 400);
$(this).text(function(i, text){
return text === "Read More" ? "Read Less" : "Read More";
})
});https://stackoverflow.com/questions/33940695
复制相似问题