我正在构建一个wp主题,调用所有的页面制作到主页。这些页面(post) id使用以下php id="post-<?php the_ID(); ?>"
动态命名,它们最终被命名为#post-1, #post-2, #post-3等…
每个实例都以最小化状态调用主页,但每个实例都有一个按钮,允许用户最大化该部分的内容。我是通过使用jQuery来实现这一点的,当按钮被单击时,将类添加到嵌套在该部分的某些元素中。
问题是我不知道如何隔离只有在其中按钮嵌套的部分。目前,当用户单击按钮时,它将类添加到主页上的每个实例(每个页面(帖子)都被调用到主页)。
有人知道我如何写一些jQuery,将允许我的目标每个部分单独使用动态命名的帖子,而没有实际输入#post-1, #post-2, post-3, etc...
到jQuery函数?
下面是我正在做的事情的简化版本:
$('.open-entry').click(function(){
$(".home-article").addClass("open");
});
.content {display: none;}
#home-article.open .content {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<article id="post-<?php the_ID(); ?>" class="home-article">
<header class="home-closed-entry-header">
<button class="open-entry">explore</button>
</header> <!-- .home-closed-entry-header -->
<div class="content">
...some content
</div> <!-- .content -->
</article> <!-- .home-article -->
任何帮助都是非常感激的!谢谢!
使用遍历。在事件处理程序中,this
指的是发生事件的元素。作为起点,您可以遍历所需的dom部分
closest()
可以将您带到主<article>
,然后从那里您可以使用find()
查看该实例
$('.open-entry').click(function(){
var $article = $(this).closest(".home-article").addClass("open");
$article.find('.content').doSomething();
});
根据您的示例,有几种方法可以将section
从按钮的上下文开始隔离。
如果结构始终是<section><header><button>
,那么从按钮开始,您可以向上移动两个父节点:
$("button").click(function() {
var thePost = $(this).parent().parent();
...
});
如果按钮上方只有一个section
元素,那么你可以寻找父元素,那是一个section元素:
$("button").click(function() {
var thePost = $(this).parents("section");
...
});
如果你正在寻找一个ID以"post-"开头的父节点,你可以把ID当作一个属性,并使用"attribute starts with"选择器:
$("button").click(function() {
var thePost = $(this).parents("[id^=post-]");
...
});