首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >存储在javascript变量中的html,如何更新javascript变量中的html

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

Stack Overflow用户
提问于 2016-03-08 06:32:41
回答 3查看 71关注 0票数 0

这里,

代码语言:javascript
运行
复制
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

我可以用

代码语言:javascript
运行
复制
   $('#editor', Data)[0].id=$('#editor', Data)[0].id+'1';

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

更新

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

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

也就是说,editor0,editor1,.,替换函数将取代所有编辑器,所以它不会有帮助

代码语言:javascript
运行
复制
  var editors = $('#editor', Data);
    for (var i = 0; i < editors.length; i++) {
        var subeditor = editors[i].id + i;
        editors[i].id = subeditor;
     }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-03-08 06:40:48

如果有多个具有相同ID名的ID,则可能需要通过属性找到它,并将旧的ID名称替换为如下所示的索引:

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2016-03-08 06:36:34

这将得到解决:

代码语言:javascript
运行
复制
Data.replace('name="editor"','name="editor1"')
票数 0
EN

Stack Overflow用户

发布于 2016-03-08 06:44:39

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35860569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档