为了账号安全,请及时绑定邮箱和手机立即绑定

根据元素中的索引值将属性动态添加到 html 元素

根据元素中的索引值将属性动态添加到 html 元素

慕森卡 2022-12-02 10:42:35
设想:如果 fileupload index 值为 0,则它必须在 fullHTML 中找到 fileindex=0 并动态添加更多属性。像 image-type = "png", image-timestamp="Wed Jul 22 13:48:30 EDT 2020"fileupload.forEach(function (item, index) { var fullHtml = "<div id="comments-box" contenteditable="true" data-text="Enter comment">    <a class="test-image test-upload" contenteditable="false" fileindex="0"        image-title="great_life5.jpg" href="#" target="_blank">        <span>great_life5.jpg</span></a>    <a class="test-image test-upload" contenteditable="false" fileindex="1"    image-title="greatlife_updated.png" href="#" target="_blank">        <span>greatlife_updated.png</span></a></div>"})expected output: var fullHtml = "<div id="comments-box" contenteditable="true" data-text="Enter comment">    <a class="test-image test-upload" image-id="39833" data-type="reviewImage" image-title="great_life5.jpg"        image-timestamp="Wed Jul 22 13:48:30 EDT 2020" image-type="png" contenteditable="false" href="#"        target="_blank"> great_life5.jpg</a>    <a class="test-image test-upload" image-id="39834" data-type="reviewImage" image-title="greatlife_updated.png"        image-timestamp="Wed Jul 22 13:48:30 EDT 2020" image-type="png" contenteditable="false" href="#"        target="_blank">greatlife_updated.png</a></div>" 
查看完整描述

1 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

您可以通过创建一个 dom 元素来实现这一点,该元素包含您的 html 并使用 dom api 对其进行请求,这比像文本一样解析它更干净、更容易


var fullHtml = `<div id="comments-box" contenteditable="true" data-text="Enter comment">


    <a class="test-image test-upload" contenteditable="false" fileindex="0"

        image-title="great_life5.jpg" href="#" target="_blank">

        <span>great_life5.jpg</span></a>


    <a class="test-image test-upload" contenteditable="false" fileindex="1"

    image-title="greatlife_updated.png" href="#" target="_blank">

        <span>greatlife_updated.png</span></a>

</div>`


const container = document.createElement("div")

container.innerHTML = fullHtml;

[1,2].forEach((item, index) => {

  let e = container.querySelector(`a[fileindex='${index}']`)

  e.setAttribute('yourAttribute', 'yourValue');

  e.setAttribute('image-timestamp', new Date().toString())

})


console.log(container.innerHTML)


查看完整回答
反对 回复 2022-12-02
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号