2017-04-20 198 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