我正试图找到一种方法来提醒一个没有类、名称或id的p标签的内容。它是一个名为"question"的标签的子标签,所以我想我可以直接进入它。父标签下有两个p标签,我要找的是第二个。当我运行这个时,它返回null。我不知道为什么,因为我是JQuery的新手,谢谢你的帮助。
alert($('#question').find('p').first().next().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td id="question">
<p>First</p>
<p>This is the one I want</p>
</td>
您的javascript很好。问题出在HTML上。你可能忘了把它包在桌子和tr:里
alert($('#question').find('p').first().next().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="question">
<p>First</p>
<p>This is the one I want</p>
</td>
</tr>
</table>
问题中的代码不起作用,因为当<td>
没有<table>
和<tr>
时,它会被渲染为没有<td>
:
<p>First</p>
<p>This is the one I want</p>
请参阅此处
问题是标记无效。如果没有table
和tr
元素,就不能单独拥有td
元素。因此,浏览器通过删除孤立的td
标记来修复损坏的标记。
如果你使HTML有效,它就会起作用:
alert($('#question').find('p').first().next().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="question">
<p>First</p>
<p>This is the one I want</p>
</td>
</tr>
</table>
当您在检查器中检查代码时,您可以看到由于table
和tr
标记不存在,那么您的td
标记也不存在,并且$('#question')
返回null。只需添加它们。
alert($('#question').find('p').first().next().text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="question">
<p>First</p>
<p>This is the one I want</p>
</td>
</tr>
</table>