2017-04-20 135 views
0

所以我基本上已经创建了一个快速的小提取器。我希望能够提取数据。我能够选择所有强大的元素。但出于某种原因,当我去选择p元素。我没有得到任何选择。jQuery Selection不能选择所有元素

见的js小提琴:https://jsfiddle.net/xmikedanielsx/e34he23d/1/

var h = `<h4> 
<a id="A" name="A"> </a>A</h4> 
<p> 
    <a id="Abrupt" name="Abrupt"> </a> 
    <strong>Abrupt Climate Change</strong> 
    <br/> Sudden (on the order of decades), large changes in some major component of the climate system, with rapid, widespread effects.</p> 
<p> 
    <a id="Adaptation" name="Adaptation"> </a> 
    <strong>Adaptation</strong> 
    <br/> Adjustment or preparation of natural or human systems to a new or changing environment which moderates harm or exploits beneficial opportunities.</p>` 

var el = $('<div></div>'); 
el.innerHTML = h; 

$('strong', el.innerHTML).each(function() { 
    alert($(this)["0"].innerHTML); 
}) 

$('p', el.innerHTML).each(function() { 
    alert($(this)["0"].innerHTML); 
}) 

回答

2

因为已经绑定一个DOM方法到jQuery对象。而是使用此:

el[0].innerHTML = h; 
// el.html(h); // <--or this one 

例子:

var h = '<h4><a id="A" name="A"> </a>A</h4><p>       <a id="Abrupt" name="Abrupt"> </a><strong>Abrupt Climate Change</strong><br/>Sudden (on the order of decades), large changes in some major component of the climate system, with rapid, widespread effects.</p><p><a id="Adaptation" name="Adaptation"> </a><strong>Adaptation</strong><br/>Adjustment or preparation of natural or human systems to a new or changing environment which moderates harm or exploits beneficial opportunities.</p>' 
 

 
var el = $('<div></div>'); 
 
el.html(h); 
 

 
$('strong', el).each(function() { 
 
    alert($(this)["0"].innerHTML); 
 
}); 
 
$('p', el).each(function() { 
 
    alert($(this)["0"].innerHTML); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

错误。你有没有试过你的代码?现在,强标签的其他选择器甚至不起作用。 更新:是的。反应太快。对不起。我做到了。理解你升到了一个级别。对不起,快速回复。现在感到沮丧。感谢您的回答。 – GrafixMastaMD

+1

同时在'$'选择器中传递上下文时,使用'$(SELECTOR,el)' – Rayon

+1

感谢@Rayon。进行编辑。 – Jai