我有代码:
// Get message
var PostTxt = $('#cid367', '.comment-txt').html();
PostTxt = $.trim(PostTxt);
它正在尝试从此结构中检索评论:
<div id="cid367" class="comment-wrapper">
<div class="comment-head ch-highlight">
<div class="comment-date">
<abbr class="timeago" title="2011-04-25T15:15:52.4070000">25 April 2011 at 15:15:52</abbr>
</div>
<div class="comment-author">
Written by <a id="A1" title="Visit this game makers profile" href="../../../users/Tom">Tom</a>
</div>
</div>
<table class="comment-body" width="100%">
<tr>
<td width="100" valign="top" align="center">
<a id="A2" title="Tom makes games with Construct 2" href="../../../users/Tom"><img id="Img1" title="Tom's Gravatar" class="comment-avatar" src="http://www.gravatar.com/avatar/5271d3283db957ef3a86761ed15c1696?r=pg&s=80" /></a>
</td>
<td valign="top">
<div id="ModBox" class="comment-modbox" style="margin-left:-105px;">
<a id="CommentReportPost" title="Report this post" class="s comment-report"></a>
<a id="CommentDeletePost" title="Delete this post" class="s comment-delete" onclick="DeleteComment('367');return false;" href="JavaScript:void(0)"></a>
<a id="CommentEditPost" title="Edit this post" class="s comment-edit" onclick="EditComment('367');return false;" href="JavaScript:void(0)"></a>
<a id="CommentQuotePost" title="Quote this post" class="s comment-quote" href="JavaScript:void(0)"></a>
</div>
<div class="comment-txt">
My comment text to get
</div>
</td>
</tr>
</table>
<div class="clear"></div>
</div>
但它一直返回 null。谁能告诉我这是怎么做到的?
最佳答案
你想错了。应该是
var PostTxt = $('.comment-txt', '#cid367').html();
第一个参数是子容器,第二个参数是父容器。
$(childSelector, parentSelector)
当像这样处理选择器时,通常有助于检查长度以确保选择器在使用 html 方法之前正常工作
// for debugging
alert($('.comment-txt', '#cid367').length); // if == 1 you're good
关于javascript - Jquery 获取 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5779893/