简体   繁体   English

如果p元素在jQuery之前,JQuery不会隐藏div?

[英]JQuery does not hide div if p element is before it?

I am trying to make use of a JQuery snippet to hide some content on SharePoint. 我正在尝试利用JQuery代码段在SharePoint上隐藏一些内容。 It works without the <p> element, but SharePoint has a lot of stuff in between the div so I think that's why it's not working. 它没有<p>元素就可以工作,但是SharePoint在div之间有很多东西,所以我认为这就是为什么它不起作用的原因。

JQuery: JQuery的:

jQuery(document).ready(function() {
jQuery(".ms-wpcontentdivspace").hide();
//toggle the componenet with class msg_body
jQuery(".ms-webpart-chrome-title").click(function(e)
 {
   e.preventDefault();
   jQuery(this).next("div.ms-wpcontentdivspace").slideToggle(200);
 });
});

Here's the working code: 这是工作代码:

<div class="ms-webpart-chrome-title"><h2><a href="http://google.com"><span>Hello</span>      </a></h2></div>
<div class="ms-wpcontentdivspace">Hi there. I am hidden</div>
<div class="ms-webpart-chrome-title"><h2>Another title</h2></div>
<div class="ms-wpcontentdivspace">More hidden stuff</div>

Here's the code that doesn't: 这是没有的代码:

<div class="ms-webpart-chrome-title"><h2><a href="http://google.com"><span>Hello</span></a></h2></div>
<p>some text</p>
<div class="ms-wpcontentdivspace">Hi there. I am hidden</div>
<div class="ms-webpart-chrome-title"><h2>Another title</h2></div>
<div class="ms-wpcontentdivspace">More hidden stuff</div>

Here's a Jsfiddle . 这是一个Jsfiddle Thanks! 谢谢!

The jQuery version used 1.3.x is pretty old, anyway try 使用1.3.x的jQuery版本已经很旧了,还是尝试

jQuery(document).ready(function () {
    jQuery(".ms-wpcontentdivspace").hide();
    //toggle the componenet with class msg_body
    jQuery(".ms-webpart-chrome-title").click(function (e) {
        e.preventDefault();
        jQuery(this).nextAll("div.ms-wpcontentdivspace").eq(0).slideToggle(200);
    });
});

Demo: Fiddle 演示: 小提琴

$.next() only gets the immediately following sibling, so you will want to use $.nextAll() $.next()仅获得紧随其后的兄弟,因此您将需要使用$.nextAll()

jQuery(document).ready(function() {
jQuery(".ms-wpcontentdivspace").hide();
//toggle the componenet with class msg_body
jQuery(".ms-webpart-chrome-title").click(function(e)
 {
   e.preventDefault(); 
   jQuery(this).nextAll("div.ms-wpcontentdivspace").eq(0).slideToggle(200);
 });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM