使用jQuery根据前一个内容选择元素?

时间:2014-09-18 13:45:41

标签: jquery html

举例说明:

<div id="input-content" contenteditable="true">
<p>Some text<p>
<p>Some text<p>
<p><br></p>
<p>Some text<p> <!-- I want to select the p tag after the p tag containing br -->
<p>Some text<p>

如何使用jQuery存档?

4 个答案:

答案 0 :(得分:1)

您可以使用:has()选择器

  

选择包含至少一个与指定选择器匹配的元素的元素。

&#13;
&#13;
$(document).ready(function() {
	var text = $('#input-content p:has(br)')//Find p with br tag
			.next('p') //Move to next p
			.text();
	alert(text);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input-content" contenteditable="true">
    <p>Some text<p>
    <p>Some text<p>
    <p><br></p>
    <p>I want to select the p tag after the p tag containing br </p> 
    <p>Some text<p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:$('p br').parent().next()

答案 2 :(得分:0)

试试这个

$("#input-content").find("p > br").parent().next("p");

答案 3 :(得分:0)

我建议您重构HTML并添加一些结构。使用div,span等并添加class / id属性。

根据换行符选择文本并不理想,每次输出文本结构发生变化时,您都会发现代码中断。