2

在包含<div>块列表的页面上,每个块都包含位置信息,并且在每个块之后都有<div>一个<hr>,我需要定位并删除所有不包含波士顿城市的 div。

我可以通过以下方式轻松删除这些 div: $("div.location").not(":contains('Boston')").remove();

那时我注意到剩余的剩余<hr>

首先定位并删除所有分隔线会更好吗?那么div呢?我可以用一笔 jQuery 做这两个吗?谢谢!

4

4 回答 4

3
$("div.location").not(":contains('Boston')").next('hr').remove().end().remove();​

演示

注意评论

$("div.location").not(":contains('Boston')")  // return the target div
     .next('hr')  // take the pointer to hr, next to target div
     .remove()    // remove the hr
     .end()       // return the pointer to target div.location again
     .remove();​   // remove the target div
于 2012-12-17T18:56:56.240 回答
1

我可以用一笔 jQuery 做这两个吗

并不是说它有任何“更好”,但您始终可以将其链接起来,删除next()HR,然后使用end()退后一步和remove()div,或者先删除 div 以相反的方式进行,这并不重要:

$('div.location').filter(function() {
    return $(this).text().indexOf('Boston') == -1;
}).next('hr').remove().end().remove();
于 2012-12-17T18:56:41.890 回答
1
于 2012-12-17T18:58:29.213 回答
0

Use a simple selector, then get the conjunctive hr elements left over

$("div.location:not(:contains('Boston'))").remove().add("hr+hr").remove();

EDIT: alternate avoid double dom manipulation by direct selection first

$("div.location:not(:contains('how'))").add("div.location:not(:contains('how'))+hr").remove();
于 2012-12-17T19:33:35.457 回答