我有一些需要 2 个 HTML 字符串的 JQuery。每个字符串都包含完全相同的 html,除了一个字符串中每个元素的内部文本内容会有所不同,该字符串称为 newContent,另一个字符串称为 oldContent。
我的函数:迭代oldContent,对于“可更新”类(在oldContent中)的每个元素,我们将其innerText更改为newContent中同一元素的innerText。
我的问题:它没有更改oldContent的内容,在我执行该功能后,oldContent包含完全相同的HTML(应该发生的是类可更新的元素应该具有不同的innerText )。
为什么字符串oldContent没有改变?
function insertContentIntoUpdatableElements( oldContent, newContent )
{
// Pre: oldContent & newContent must be strings of HTML returned from jquery's
// $("").html()
try
{
alert("BEFORE: "+oldContent);
var index = 0;
var oldElements = $(oldContent).find(".updatable");
var newElements = $(newContent).find(".updatable");
$(oldContent).find(".updatable").each( function()
{
var txt = $(newElements[index]).text(); alert("TEXT: "+txt);
alert("OLD TEXT: "+$(this).text());
$(this).text(txt);
index++;
alert("NEW TEXT: "+$(this).text()); // prints out CORRECT updated/changed text
});
alert("AFTER: "+oldContent); // prints out INCORRECT updated/changed text for each element of class "updatable"
return oldContent;
}
catch(ex) { alert("In insertContentIntoUpdatableElements(): "+ex); return "FAILED"; }
}
最佳答案
这应该可以解决问题。
function insertContentIntoUpdatableElements( oldContent, newContent )
{
var result = $(oldContent);
var oldElements = result.find(".updatable");
var newElements = $(newContent).find(".updatable");
$(oldElements).each(function(index, el)
{
$(oldElements[index]).text($(newElements[index]).text());
});
return result;
}
查看 jsFiddle 上的工作演示:http://jsfiddle.net/ZZVgh/
关于javascript - 使用 jQuery 更改 HTML 字符串 : wont update the string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7643082/