簡體   English   中英

如何從ajax過濾返回數據的正文html?

[英]How do I filter body html the returned data from ajax?

我的目的是,我想從數據中取出特定的html並僅更新該區域。

如何從jQuery.ajax過濾返回的數據?

這個鏈接是一個老帖子,但我確實有完全相同的問題。

從鏈接給出的解決方案是$("[ref=B]").html(data).find( '[ref=A]' );

但是,如果我這樣做,整個頁面將首先在<span ref='B'>上寫,然后找到它內部的選擇器.....

找到'[ref = A]'的替代方法是

html = $(data).filter('[ref=B]').find('[ref=A]').html() // this way will work

這些都不會奏效

$(data).find('[ref=A]').html();
$(data).filter('[ref=A]').html();
$(data).filter('body').html();
$(data).find('body').html();

HTML

`<body>

<span ref='B'><span ref='A'>abc</span></span>

</body>`

JS

 $(function() {
$.get(window.location.pathname + window.location.search, function(data){ alert(data);});
 });

返回的數據

<html>
<body>
    <span ref='B'><span ref='A'>abc</span></span>
</body>
</html>

我的問題是,是否有一個解決方案來從$ .ajax返回的數據中過濾body的html? 喜歡

body_html = $(data).??????? 

然后我可以做任何我想做的事,比如

body_html.find('xxxx');

非常感謝您的建議。

您可以使用DocumentFragment來模擬您的html並進行搜索,而無需將其附加到DOM

// Create your DocumentFragment to be able to work without DOM
var body_html = document.createDocumentFragment();

// Convert and append data from your jQuery to work with fragment
body_html.appendChild($(data)[0]);

// Now you can select using your jQuery
var $body_html = $(body_html);

// Now you can use the find or whatever you want, like if it was in the DOM
$body_html.find('.foo');

// Or you can append in your current document, 
// but attention, after it the fragment reference is erased
$body_html.appendTo(document.body); 
// now you need to get reference again from body, 
// because your fragment doesn't exists anymore.

// So... if you try:
console.log(body_html); // undefined
console.log($body_html); // jquery over undefined, probably just a jquery useless

// At this point you will need to reference from DOM to continue manipulation
$body_html = $(document.body);
// Now I'm ready to continue the work
// This var is like your DocumentFragment, but already on DOM.

你也可以在jQuery模板化$(data).filter('.foo')進行過濾,但正如你在本次測試中看到的那樣,你的表現會下降很多。

$("[ref=B]").append($(data).find("[ref=A]"));

你在問題中的方式,最后一部分find( '[ref=A]' )是沒用的。

[編輯]另外,另一個問題是超過2年。 對於最新版本的jQuery,您可能需要其他引號:

$("[ref='B']").append($(data).find("[ref='A']"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM