0

我想在找到“电池”字符串之后找到下一句。文本没有标签,只有引号。

<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah">battery</h2> << using this string "battery"
"coucou test tt test" << text to find
<h2 class="inshallah">dress</h2>
</html>

我试过了,但是如果之后没有标签,它就不起作用

    var test = $('.inshallah').filter(function() {
    return $(this).text().trim() === "battery";
    }).next().text();
    
    console.log(test)

4

4 回答 4

2

你在正确的轨道上。dress您的代码返回.next仅选择下一个兄弟元素,您要选择的是下一个textNode。jQuery 没有用于选择下一个textNode. 您可以使用 DOMHTMLElement.nextSibling属性:

var text = $('.inshallah').filter(function() {
    return $(this).text().trim() === "battery";
}).get(0).nextSibling.textContent;
于 2018-08-16T18:50:47.940 回答
1

$(document).ready(function() {

  $("h2").each(function(i, e) {//or .inshallah, it's the same
    if (e.innerText == "battery") {
      alert(e.nextSibling.data);
    }
  })

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah">battery</h2>
"coucou test tt test"
<h2 class="inshallah">dress</h2>

</html>

于 2018-08-16T18:55:40.730 回答
0

您需要指定 html dom 元素 p

解决方案 1

<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah">battery</h2>
<p>coucou test tt test</p>
<h2 class="inshallah">dres</h2>
</html>

var test = $('.inshallah').filter(function() {
   return $(this).text().trim() === "battery";
}).next().text();

console.log(test)

解决方案 2

<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah battery">battery</h2>
<p>coucou test tt test</p>
<h2 class="inshallah">dress</h2>
</html>

$( ".battery" ).next().css( "background-color", "red" );

我希望你能明白。

于 2018-08-16T18:48:39.973 回答
0
$("html").html().split("battery")[1].split("h2>")[1].split("<h2")[0]

虽然不建议这样做。您应该提供适当的属性,例如类、id 或数据属性。永远不要让数据搁浅。建议将数据封装在某个标签中(最好是 div)。

于 2018-08-16T18:59:34.970 回答