简体   繁体   English

用图像更改li内的文本

[英]Change text inside li with image

I want to change the text inside a li. 我想更改li内的文本。 But this li has got an img. 但是这个李有一个img。 Here the html: 这里的HTML:

<div>
<ul>
<li><b><img src="../../../Images/folder1/image1.png">Text1</b><i>0</i></li>
<li><b><img src="../../../Images/folder1/image2.png">Text2</b><i>1</i></li>
<li><b><img src="../../../Images/folder1/image3.png">Text3</b><i>2</i></li>
<li><b><img src="../../../Images/folder1/image4.png">Text4</b><i>3</i></li>
<li><b><img src="../../../Images/folder1/image5.png">Text5</b><i>4</i></li>
</ul>
</div>

I am trying this: 我正在尝试:

$("li").each(function () {
$(this).text(sometext);
})

But it is replacing all, including the img. 但是它正在替换所有内容,包括img。 I only want to change the text: Text1,Text2,... 我只想更改文本:Text1,Text2,...

Any ideas? 有任何想法吗?

Thanks! 谢谢!

To get to the textnodes within an element you need to use contents() and then filter() by nodeType. 要到达元素内的textnodes,您需要使用contents() ,然后通过nodeType进行filter() You can then use replaceWith() to change the text. 然后,您可以使用replaceWith()更改文本。 Try this: 尝试这个:

$('li:first b').contents().filter(function() {
    return this.nodeType == 3;
}).replaceWith('foo');

Example fiddle 小提琴的例子

I obviously hard-coded this to use the first li element, but you can change the selector as needed. 我显然将其硬编码为使用第一个li元素,但是您可以根据需要更改选择器。

You could also do it like this: 您也可以这样:

http://jsfiddle.net/YNLXQ/ http://jsfiddle.net/YNLXQ/

$("li b").each(function () {
   this.childNodes[1].textContent = "32323";
})

Store the image in a separate variable and after replacing the text prepend the image back. 将图像存储在一个单独的变量中,并在替换文本后在图像之前添加图像。

$("li b").each(function () {
    var $img = $(this).find('img'); 
    $(this).text(sometext).prepend($img);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM