html存储在javascript变量中,如何在javascript变量中更新该html

html stored in javascript variable,how to Update that html inside javascript variable

本文关键字:变量 html javascript 更新 存储      更新时间:2023-09-26

在这里,

var data = '
<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 100%;">    
    <tbody>     
        <tr>
            <td>
                <textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2">&copy; 2016 Vishmay Shah</td>
        </tr>
    </tbody>
</table>
<p>&nbsp;</p>'

我想在数据变量中使用 jquery 将编辑器的 id 更新为 editor1

我可以使用它访问它

   $('#editor', Data)[0].id=$('#editor', Data)[0].id+'1';

但我想将更新的 HTML 保存回数据变量中。


更新

将有多个具有相同 id 编辑器的编辑器。

实际上,我想通过附加索引来使其唯一。

那就是编辑器0,编辑器1,...,替换函数将替换所有编辑器,因此无济于事

  var editors = $('#editor', Data);
    for (var i = 0; i < editors.length; i++) {
        var subeditor = editors[i].id + i;
        editors[i].id = subeditor;
     }

如果您有多个具有相同 ID 名称的 ID,也许您需要按属性查找它并将旧 ID 名称替换为索引,如下所示:

var Data = '<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 100%;">    <tbody>     <tr><td><textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea><textarea cols="80" id="editor" name="editor" rows="10">This is my textarea to be replaced with Editor.</textarea></td>     </tr>       <tr>            <td colspan="2">&copy; 2016 Vishmay Shah</td>       </tr>   </tbody></table><p>&nbsp;</p>';
// this will look the element with ID editor
// and replace element with index
var newElem = $(Data).find('[id="editor"]').attr('id', function(i, old) {
     return old + i;
}).end();
console.log(newElem)

DEMO(检查元素以查看实际 ID)

这将解决:

Data.replace('name="editor"','name="editor1"')

更新属性id多个元素可以使用:last.length .prop(function(name, propertyValue){}).attr(function(name, propertyValue){}) 来实现。

另一种方法是尝试使用相同的className替换,例如; .editor ,表示多个id以名称开头,在多个元素处以数字结尾。使用.length确定当前正在处理的元素。