使js在数据属性内拾取HTML代码?



在data属性中有一段html代码。

<a href="#" data-type="video" data-video='<div class="wrapper"><div class="video-wrapper"><video id="player" playsinline width="960" class="pswp__video" controls data-poster="img/poster.jpg"><source src="video/soulmv-low.mp4" type="video/mp4"></video></div></div>'></a>

是否有任何方法使js拾起数据属性内的代码并修改它,像往常一样?

谢谢!

如果您想将html加载为DOM Element以轻松地修改它而不是字符串,您可以执行以下操作:

const link = document.querySelector('a')
const dataVideoAttribute = link.getAttribute('data-video')
const dataVideoElement = createElementFromString(dataVideoAttribute)

创建JS Object的辅助函数如下所示

/**
* Create a new HTML Object from an HTML code as string
* and returns the object.
* 
* @params elementAsString: HTML code as a raw string
*
* @returns object: HTML Element created from raw string
*/
function createElementFromString(elementAsString) {
var div = document.createElement('div');
div.innerHTML = elementAsString.trim();
// Change this to div.childNodes to support multiple top-level nodes.
return div.firstChild;
}
然后,你可以用你的JS代码做正常的例程,例如:
dataVideoElement.setAttribute('new-att', '1')

如果你想更新和保存html属性,你可以:

link.getAttribute('data-video', dataVideoElement.outerHTML)

获取数据属性,例如,如果属性为data-type="video"

const type = document.getElementById('item1').dataset.type;

设置

document.getElementById('item1').dataset.type = "mp3"

最新更新