作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
您好,我正在尝试从另一个 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 & Conditions</a>.</div>
</div></div>
</form>
我试图从上面的文本中获取 rewards_point_display
div 文本,但它不起作用。
有什么帮助吗?
谢谢
最佳答案
IMO,你应该使用 jQuery.parseHTML()
将字符串解析为 DOM 节点数组。
var bad = $.parseHTML(result);
或
使用.filter()
console.log($(result).filter('#rewards_point_display').html());
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>
关于javascript - 如何从html内容中获取div文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39952644/
我是一名优秀的程序员,十分优秀!