只更改包含img的li中的文本
我有这个HTML代码
- criteria 1
- criteria 2
我有动态更改li文本的function
$("input#criterion_name").live("keyup",function(e){ var newText = $("input#criterion_name").val(); if(newText){ $("ul.criteria > li.selected").html(newText); } else{ // can't leave the text filed empty $("#criterion_name").addClass("error"); }
问题是当我在输入文本中键入文本时,li元素中的图像被删除。 我只想更改li元素中的文本
您应该将文本包装在自己的元素中,就像span
。 然后你可以像这样定位:
$("ul.criteria > li.selected > span.thetext").html(newText);
此外,id属性不应只是数字,不应在文档中多次使用,即它应该是唯一的。 您有几个实例,其中id="1"
使用.text()
代替.html()
编辑
$(".criteria > li").contents().filter(function(){return this.nodeType == 3}).first().replaceWith(newText);
将名称包含在span
的li
span
(或者您认为有效的任何元素)。 然后改变span
。
小提琴: http : //jsfiddle.net/LLPya/1/
HTML:
- criteria 1
- criteria 2
jQuery的:
$('#criterion_name').keyup(function() { var newText = $(this).val(); if (newText) { $('#1 span.criteria_name').html(newText); } });
根据您的选择器,您的HTML不完整,所以我只添加了一个文本框,并更改了第一个li
的名称。
您可以使用nodeType属性仅选择文本并替换它。无需在span中包含其值。
试试这个代码
$("ul.criteria > li").contents().filter(function() { return (this.nodeType != 1 && this.textContent != '\n') }).replaceWith('Older Text replaced...');
- 使用
.contents()
获取li中的所有内容。 - 然后过滤并仅选择没有回车符的文本节点。
- 然后用新文本替换
检查FIDDLE
我更喜欢安迪的回答,因为它还允许你进一步操纵那个跨度。
所以你的HTML代码将成为:
- criteria 1
- criteria 2
由于元素ID 在HTML文档中必须是唯一的 ,并且按ID查找是最快的jQuery选择器 ,因此无需按元素类型和 ID进行选择。 不推荐使用 “ .live()方法, ”; 我们建议使用.on()方法。 所以,当我们添加Andy的解决方案时,你的jQuery将成为:
$('#criterion_name').on('keyup', function() { var newText = $(this).val(); if(newText.length){ $('ul.criteria > li > span.label_text').html(newText); } else{ // can't leave the text filed empty $('#criterion_name').addClass('error'); } });
看一下我的小提琴,看一个有效的例子 。