jquery似乎无法在没有包裹父元素的情况下找到元素。
var data = '<div id="target"> This is what I have </div>';
var result = $(data).find("#target").text();
alert("Without targetParent =>" + result); //Get empty result
data = '<div id="targetParent"><div id="target"> This is what I have </div></div>';
result = $(data).find("#target").text();
alert("With targetParent =>" + result); // Get the "target" element
https://jsfiddle.net/z5roxurq/
不知道为何如此。
答案 0 :(得分:0)
答案 1 :(得分:0)
find()
方法搜索选择器中的后代元素。要过滤所选元素中的元素,请使用 filter()
方法。
var result = $(data).filter("#target").text();
var data = '<div id="target"> This is what I have </div>';
var result = $(data).filter("#target").text();
alert("Without targetParent =>" + result); //Get empty result
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
outerHTML
属性。
var result = $(data).filter("#target")[0].outerHTML;
var data = '<div id="target"> This is what I have </div>';
var result = $(data).filter("#target")[0].outerHTML;
alert("Without targetParent =>" + result); //Get empty result
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
如果只有单个标记,则不需要 filter()
方法,而是使用索引获取dom对象。
var result = $(data)[0].outerHTML;
var data = '<div id="target"> This is what I have </div>';
var result = $(data)[0].outerHTML;
alert("Without targetParent =>" + result); //Get empty result
&#13;