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

时间:2016-03-08 06:32:41

标签: javascript jquery html

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

中加载它
 $('body').html(Data);

谢谢

更新

可能有多个编辑器具有相同的id编辑器,实际上我想通过附加index-&gt;使其唯一;那就是editor0,editor1,...,替换函数将取代所有编辑器,所以它无济于事

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

3 个答案:

答案 0 :(得分:1)

如果你有多个具有相同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)

答案 1 :(得分:0)

这样可以解决:

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

答案 2 :(得分:0)

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

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