2012-04-02 181 views
0

我試圖從使用Javascript和jQuery的html文件中獲取包含文本的節點。 如果我有像 `從html文件中提取文本

<div>txt0 
<span>txt1</span> 
txt2 
</div> 

How can I select elements that meets this criteria?? Meaning, I need to retrieve the DIV and the span`一個節點,它甚至會更好,知道文本的位置。

我試圖讓文本在隨後的函數中用圖像替換它。 我想這

`

$('*').each(function(indx, elm){ 
    var txt = $(elm).text(); 
    // my code to replace text with images here 
}); 

`

但它不會獲得所需的結果..它所有的分析中第一個元素,並完全改變的HTML。

+0

你想選擇所有在他們的文本中的元素? – Lix 2012-04-02 22:37:01

+0

在你操作之後'

txt0txt1txt2
'變成了什麼? – 2012-04-02 22:41:53

+0

@lix是的, @ JuanMendes:當我找到它們時我會改變它們 – zeacuss 2012-04-03 13:20:05

回答

1

我不確切地知道你想要解決什麼,但也許你可以對你的選擇器更具體一些?

$("div span").text(); // returns 'txt1' 
$("div").text();  // returns 'txt0txt1txt2' 

通過增加IDS和/或類你的HTML,你可以很具體:

<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div> 

...

// returns all spans with class 
// "middlename" inside divs with class "name" 
$("div.name span.middlename").text(); 

// returns the first span with class 
// "middlename" inside the fourth div 
// with class "name" 
$("div.name[3] span.middlename[0]").text(); 

jQuery有相當good documentation這些選擇的。

如果這沒有幫助,請考慮解釋您嘗試解決的問題。

0

您的標記結構有點不安。考慮更換爲這樣的事情

<div> 
    <span>txt0</span> 
    <span>txt1</span> 
    <span>txt2</span> 
    </div> 

然後使用jQuery

$("div span").each(function(k,v) { 
    $(this).html("<img src=\""+v+".jpg\" />"); //replace with the image 
});