使用 jQuery 切换下一个元素
我的 this
元素有问题(我知道 this
是如何工作的)。
我有很多这样的 html 结构。当我单击 a 按钮时,必须显示带有 extra-options
类的 div。但由于我在整个过程中重复了很多相同的 html 结构,因此当我单击按钮时,也会显示所有其他 div 选项。
我该如何修复它?
这是 JavaScript:
var buttonSubmit = $(".extra-options .details a.button");
buttonSubmit.click(function (e) {
e.preventDefault();
var extraOptions = $(".extra-options-tickets");
if($(".extra-options-tickets").is(":visible")) {
extraOptions.hide();
} else {
extraOptions.fadeIn(450);
};
});
这是 html:
<p class="actions">
<a href="#" class="button" title="Toevoegen"><span>Toevoegen</span></a>
</p>
<div class="extra-options-tickets" style="display: none; ">text</div>
提前感谢您的帮助。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更改您的代码,以便您在单击的链接之后直接获得额外的选项 div,如下所示:
Change your code so that you get the extra options div directly after the clicked link like this:
描述
您应该使用 jQuery.parent() 和 jQuery.next() 来完成此操作。
查看示例和此jSFiddle 演示。
示例
Html
jQuery
更多信息
Description
You should use
jQuery.parent()
andjQuery.next()
to get this done.Check out the sample and this jSFiddle Demonstration.
Sample
Html
jQuery
More Information
请参阅我为您制作的示例: http://jsfiddle.net/manuel/PmNwh/
我使用jquery
next()
函数获取第一个.extra-options-tickets
see this example I made for you: http://jsfiddle.net/manuel/PmNwh/
I use the jquery
next()
function to get the first.extra-options-tickets
this
元素表示在您的情况下调用操作的元素,它是元素。
看起来您只想显示下一个
而不是全部,所以您需要这样思考:
在此代码中,如果触发
click
的是(您的选择器),我该如何到达
;
我想要 展示?从
中,您可以导航到上一个元素,即
和 < strong>next 元素(
将其转换为代码:
您始终可以制作更通用的元素,这样您就可以安全地在两者之间添加更多元素,例如:
而不是调用
.prev()
(前一个元素),找到最接近的具有actions
类的元素,然后从那里找到 DOM 中具有类的下一个元素extra-options-tickets
,翻译:The
this
element represents the element that invoked the action witch in your case, it's the<a>
element.and it seams you want to only show, the next
<div class="extra-options-tickets">
and not all of them, so you need to think like this:In this code, if what fires the
click
is the<a>
(your selector), how do I go to reach the<div>
I want to show?From
<a>
you can navigate to the previous element, witch is the<p class="actions">
and the next element (the<div>
) is the one I want...translating this to code:
you can always make more generic so you can safely add more elements in between, for example:
instead of calling the
.prev()
(previous element), find the closest elemnt with a class ofactions
and from there, find the next element down the DOM with a class ofextra-options-tickets
, translating: