Ajax响应使用Find查找HTML片段 [英] Ajax Response Finding HTML Fragments Using Find
问题描述
$ b
code><!DOCTYPE html>
< html>
< body>
< div id =dashboard>
< div id =dash2>
< h1>你好< / h1>
< / div>
< / div>
< / body>
< / html>
在我的Ajax Success代码中是这样的。
success:function(response,status){
console.log($(response).find('#dashboard')。html());
$ b $ p
$ b 在控制台上输出未定义
。不过当我修改响应页面(我创建了一个嵌套div)时, code><!DOCTYPE html>
< html>
< body>
< div id =div1>
< div id =dashboard>
< div id =dash2>
< h1>你好< / h1>
< / div>
< / div>
< / div>
< / body>
< / html>
来自我的Ajax Success代码的行返回了 console.log($(response ).find('#dashboard')。html());
返回了
< div id =dash2>
< h1>你好< / h1>
< / div>
我的问题,执行 console.log ($(response).find('#dashboard')。html());
它给了我一个未定义的,但是第二个HTML(嵌套在div中的)给了我内容 #dashboard
(我期望得到的那个)。
据我所知,这是一个依赖于浏览器的行为,标签作为一种卫生措施,例如< head />
。
在执行时未找到 #dashboard
的原因
< code $ $(response).find('#dashboard')
#dashboard
已成为卫生条件下的根元素, .find()
与不在根本身。
我通常会避免这个问题,通过一个空的< div>
。
$(< div />)。html(response).find('#dashboard')
I was doing some test with JQuery find , I have an html response coming from an AJAX request, so initially the result would be this.
<!DOCTYPE html>
<html>
<body>
<div id="dashboard">
<div id="dash2">
<h1>Hi</h1>
</div>
</div>
</body>
</html>
In My Ajax Success code is this..
success : function(response,status) {
console.log( $(response).find('#dashboard').html() );
}
Upon printing it on the console that gives me an undefined
.
However when I modify the response page(I created a nesting div) to this
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<div id="dashboard">
<div id="dash2">
<h1>Hi</h1>
</div>
</div>
</div>
</body>
</html>
The line from my Ajax Success code returned console.log( $(response).find('#dashboard').html() );
returned the
<div id="dash2">
<h1>Hi</h1>
</div>
My Question, How come on the first HTML when doing the console.log( $(response).find('#dashboard').html() );
it gave me an undefined, however on the second HTML(the one nested in the div) gave me the the contents of #dashboard
(which the one I am expecting to get.
As far as I know it is a browser dependent behavior to which tags to drop as a measure of sanitation, e.g. <head/>
.
The reason for not finding #dashboard
while executing
$(response).find('#dashboard')
is most probably because #dashboard
has become the root element after the sanitation, and .find()
matches against the descendant elements not on the root itself.
I normally to avoid this problem do this over an empty <div>
.
$("<div/>").html(response).find('#dashboard')
这篇关于Ajax响应使用Find查找HTML片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!