繁体   English   中英

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

[英]Jquery Ajax, How to Grab Specific Element(s) of Source Page

尝试通过简单的代码示例学习Ajax-jQuery,我将这两个html文件设置为:index.html和source.html。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>

现在我的问题是如何获取特定元素而不是将所有元素都添加到索引页中? 例如,如何过滤请求对象以仅获得类“ test1”或仅获得所有div

我也不太了解“数据”参数在页面中的含义。

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>

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

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

现在, test1_elements将包含来自source.html的类为test1所有元素。

您可以通过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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM