[英]add attributes dynamically to the html element based on Index value in the element
設想:
如果 fileupload 索引值為 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>"
您可以通過創建一個包含 html 並使用 dom api 請求它的 dom 元素來實現這一點,這比像文本一樣解析它更干凈、更容易
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.