如何切换除<b>标签之外的所有内容

时间:2016-12-21 01:59:14

标签: jquery

我想为我的博客创建一个摘要视图,我认为可以使用jQuery完成。 我的想法是隐藏页面上的每个元素,不包括h1,h2,img和b标签。 关于我如何做出选择的任何想法?

这是一个简单的例子:

原始状态:

h1: Blog Title, it remains
p: First sentence of the post
p: Second sentence of the post
img: /foo/bar.png, it remains
b: This is a bold text, it remains

点击jQuery按钮时:

h1: Blog Title, it remains
img: /foo/bar.png, it remains
b: This is a bold text, it remains

我一直在使用:not selector和.not方法,但我似乎无法实现我正在寻找的东西。

与往常一样,任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

您可以使用.nextUntil().hide()

&#13;
&#13;
$("button").on("click", function() {
  $("h1").nextUntil("img", "p").hide();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click</button>
<h1>Blog Title, it remains</h1>
<p>First sentence of the post</p>
<p>Second sentence of the post</p>
<img src="/foo/bar.png" alt="it remains" />
<b>This is a bold text, it remains</b>

<h1>Blog Title, it remains</h1>
<p>First sentence of the post</p>
<p>Second sentence of the post</p>
<img src="/foo/bar.png" alt="it remains" />
<b>This is a bold text, it remains</b>
&#13;
&#13;
&#13;

  

但我看到的唯一问题是当

中有标签时,   因为我只想隐藏不在B标签上的p内容

如果在<p>元素被点击后,预期结果是包含<b>元素的button元素,则可以使用选择器"p:not(:has(b))"作为{.nextAll()的第二个参数1}}从返回的jQuery对象中排除包含p元素的b元素。

&#13;
&#13;
$("button").on("click", function() {
  $("h1").nextUntil("img", "p:not(:has(b))").hide();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click</button>
<h1>Blog Title, it remains</h1>
<p>First sentence of the post</p>
<p><b>Second</b> sentence of the post</p>
<img src="/foo/bar.png" alt="it remains" />
<b>This is a bold text, it remains</b>

<h1>Blog Title, it remains</h1>
<p><b>First</b> sentence of the post</p>
<p>Second sentence of the post</p>
<img src="/foo/bar.png" alt="it remains" />
<b>This is a bold text, it remains</b>
&#13;
&#13;
&#13;