Jquery Ajax,如何获取源页面的特定元素

时间:2012-11-15 08:34:21

标签: jquery ajax

尝试通过简单的代码示例学习Ajax -jQuery我有两个html文件:index.html和source.html.the inex.html如下:

enter code here
<!DOCTYPE html>
 <html>
 <head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
 <script>
  $(document).ready(function() {
   $('button').click(function(){
   $.get('source.html', function(data) {
   $('.result').html(data);
   });
  });
 });
 </script>
 <title>Main Page</title>
 </head>
 <body>
 <button>Load Page</button>
 <div class="result"></div>
 </body>
 </html>

和source.html为:

enter code here
<!DOCTYPE html>
<html>
<head>
<title>Source Page</title>
</head>
<body>
<div class="test1">Hello Ajax!</div>
<div class="test2"> Again Hello Ajax!</div>
<div class="test1">WoW Ajax!</div>
 <p> The html() method sets or returns the content(innerHTML) of the selected... </p>
 </body>
</html>

现在我的问题是如何获取特定元素而不是获取索引页面中的所有元素?例如,我如何过滤请求对象只是从页面源获取所有div“test1”或仅

。我也不太了解“data”参数在

enter code here
$.get('source.html', function(data) {
$('.result').html(data);
你能告诉我这是什么意思吗?

来自控制台的数据:

<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
</head>
<body>
<div class="test">Hello world!</div>
<div class="test1">Hello Ajax!</div>
<div class="test2"> Again Hello Ajax!</div>
<div class="test1">WoW Ajax!</div>
<p> The html() method sets or returns the content (innerHTML) of the selected   elements.When this method is used to return content, it returns the content of the FIRST   matched element. When this method is used to set content, it overwrites the content of ALL matched elements.</p>
 </body>
 </html>

2 个答案:

答案 0 :(得分:1)

获得ajax调用的响应后,您可以通过以下方式找到元素:

$.get('source.html', function(data) {
   test1_elements = $(data).find('.test1')
});

test1_elements现在将包含source.html中包含类test1的所有元素。

答案 1 :(得分:0)

您可以按ID或类抓取特定元素:

var $byids= $('#id');
var $byclass= $('.class');

函数中的data参数包含整个响应数据,即source.html显示的内容。

您可以使用

var $div= $(data).find('#divid'); 

从数据中选择内容。

更新: 你有2个test1元素。 以下将获取每个的html,并将它们拼接在一起。 最后一行显示文档中“test”类的所有元素中的摘要。

$.get('source.html', function(data) {
    var $test1_elements = $(data).find('.test1');
    var summary= '';
    $test1_elements.each({function(){ summary+= $(this).html(); });
    $('.test').html(summary);
});