2012-04-02 179 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 
});