如何从html内容中获取div文本

时间:2016-10-10 06:48:32

标签: javascript jquery html css ajax

您好我正在尝试从另一个html页面获取div数据。对于这些我通过$.ajax({});获取html数据它已经返回了一堆html内容,我试图获取div文本,但它返回空。

我的代码是:

$(document).ready(function() {

    $.ajax({
      url:'/Myrewards.asp',
      type:'GET',
      success: function(data) { 
        var result = $(data).filter("#content_area").html();
        var result_1 = $(data).filter("#rewards_point_display").text();
        console.log(result);
      }
   });
});

result在html代码下方返回。

<form action="" method="post">
<div id="div_articleid_141">
<link type="text/css" rel="stylesheet" href="/a/c/myrewards.css">    <div id="rewards_content">    <h3>MyRewards - Reap the rewards with every purchase</h3>    It pays to go with MyRewards. Every time you make a purchase with [your company or website's name], you'll receive points [if product based, then] for the product(s) you purchase [if total amount of purchase, then] based on your total purchase amount. It's a great way to save on your next purchase whether it's for you or someone special.    <h4>Here's how it works:</h4>    <ol>   <li>Once you've placed your order and it has shipped, your MyRewards Point will be redeemable in [X] days.</li>   <li>To view your MyRewards, simply go to <a href="/MyRewards.asp">MyRewards</a>.</li>   
<li>Enter the total amount (in points) you'd like to redeem below (X points = $X).</li>   <li>You're now ready to save on your next purchase. Upon placing your order, your available MyRewards will automatically be deducted from the total purchase amount.</li>  
</ol>    <div id="rewards_point_display">  Available Points: 100<br>  Pending Points: 0  </div>    <input id="points_to_redeem" name="points_to_redeem" value="100" type="text"> 
<input id="redeem_now_button" src="/v/vspfiles/templates/253/images/Buttons/btn_redeem.gif" value="Redeem" name="go" alt="Redeem" type="image">    
<div id="rewards_terms">Want to learn more about MyRewards? For more MyRewards information, see the <a href="articles.asp?ID=140">Terms &amp; Conditions</a>.</div>
</div></div>

</form>

从上面的文字我试图获得rewards_point_display div文本,但它不起作用。

任何帮助?

由于

2 个答案:

答案 0 :(得分:2)

IMO,您应该使用jQuery.parseHTML()

将字符串解析为DOM节点数组。

var bad = $.parseHTML(result);

使用.filter()

console.log($(result).filter('#rewards_point_display').html());

Reference

var result = "<div>First Div</div><div id='rewards_point_display'>Text of rewards_point_display</div>";

//Use filter
console.log($(result).filter('#rewards_point_display').html());


//use parseHTML
var data = $.parseHTML(result);
$(data).each(function() {
    console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:2)

尝试jQuery load(),如下所示:

var url = '/Myrewards.asp';
$('.whereyouwanttoinsert').load(url + ' #rewards_point_display');