2017-02-19 18 views
0

這可能是漂亮的小白,但有這種情況下,我無法找出jQuery選擇我需要.... 所以,讓HTML像我應該使用什麼jQuery選擇器來獲得跨匿名孩子?

<span style="color:red;">Gender:</span>Drama<br> 
<span style="color:red;">Country:</span>USA<br> 

我應該用什麼jQuery選擇得到「戲劇」? 在此先感謝

+1

手段由於 「戲劇」 是不是'HTMLElement',你會需要https://api.jquery.com/contents/ – haim770

+0

你可以在這裏找到答案[here](http://stackoverflow.com/questions/6388507/use-jquery-to-select-text-not-in-an-element ) – tkhuynh

回答

1

首先,您需要識別<span>元素,然後在文本節點之後獲取文本節點。由於span元素沒有任何唯一的內容,因此可以使用它們在父元素中找到的順序來標識它們。

您可以使用僞選擇器,如:first-child:nth-child來這樣做。

確定跨度後,需要選擇下一個節點並檢索其值。

一個例子:

console.log($('span:first-child')[0].nextSibling.nodeValue)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
<span style="color:red;">Gender:</span>Drama<br> 
 
<span style="color:red;">Country:</span>USA<br> 
 
</div>

+0

非常感謝你,@motanelu。我略微修改了你的選擇器以實現我的需要: 'alert($('span:contains(「Gender」)')[0] .nextSibling.nodeValue);' – glezo

0

你的問題不是很清楚。

我想你的內容有一個父(<p>?) 我有你想要做一個複雜的方式什麼的感覺,而且它可以更簡單。

爲什麼不把你必須在其他跨度選擇的內容? :

var textContent = new Array(); 
 
$('p .selector').each(function() { 
 
    textContent.push($(this).text()); 
 
}); 
 

 
console.log(textContent[0]); 
 
console.log(textContent[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p> 
 
    <span style="color:red;">Gender:</span><span class="selector">Drama</span><br> 
 
    <span style="color:red;">Country:</span><span class="selector">USA</span><br> 
 
</p>

+0

**很清楚**: I不能修改html。正如我所說的,我需要解析並提取指定的令牌。 – glezo

0

基於@montalenu的答案,我實現了我的目標由 alert($('span:contains("Gender")')[0].nextSibling.nodeValue)‌​;

相關問題