如何使用jquery获取变量中的元素文本?

时间:2016-10-10 15:42:38

标签: javascript jquery html html-parsing selector

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">&#160;</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow <a href="/Shared%20Documents/EBS%20Page%20Refresh%20Instructions_rkc.pdf">these instructions</a>. &#160;</div>';           
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
    str += $(this).text();
})

如何获取以markup开头的ExternalClass中所有div的内容?

2 个答案:

答案 0 :(得分:2)

$(markup)选择器包含所有ExternalClass课程,您无法使用.find(),因为它不会影响任何匹配的孩子。您需要使用.filter()来过滤所选元素。

var markup = "<div...";
var str = "";
$(markup).filter("div[class^='ExternalClass']").each(function(){
    str += $(this).text();
})

&#13;
&#13;
var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">&#160;</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow <a href="/Shared%20Documents/EBS%20Page%20Refresh%20Instructions_rkc.pdf">these instructions</a>. &#160;</div>';
$(markup).filter("div[class^='ExternalClass']").each(function(){
    console.log($(this).text());
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

jQuerys .find()仅循环遍历您选择的特定HTML的子项。您的变量markup没有具有拟合类选择器的子项。 我能想象得到解决的最简单的方法是将markup中的所有内容包装在另一个div中,然后使用你的jQuery选择器 - 它可以工作:

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">&#160;</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow <a href="/Shared%20Documents/EBS%20Page%20Refresh%20Instructions_rkc.pdf">these instructions</a>. &#160;</div>';
markup = '<div>' + markup + '</div>';
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
    str += $(this).text();
})