如何将字符串解析为html,或者如何通过单击按钮动态添加复杂的html



当我点击按钮时,我需要插入这个html树

<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>

我试过这个代码,但它给我返回了一个正文标签,里面有我的html

var stringToHTML = function (str) {

var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};

我需要在上传按钮之前动态添加前面的html元素(我使用了一个before((方法,里面有stringToHTML函数,它很有效(。有一种更简单的方法可以做到这一点?。因为我了解到documen.createElement不适用于复杂的参数。

感谢所有社区对我的帮助,即使是在我之前的问题上。

您可以创建一个带有模板文本的html变量,在其中您可以编写html语义,然后您可以使用insertAdjacentHTML((

使用模板字符串来包含HTML,单击按钮时使用insertAdjacentHTML将其添加到现有元素中。

const str = `
<div class="img-wrapper">
<img id="immagine_preview" width="200px" height="200px" data-id_immagine="1">
<button type="button" class="rimuoviImg">
<span class="fa fa-times"></span>
</button>
</div>
`
// Cache the element you want to markup to appear,
// and the button
const div = document.querySelector('div');
const button = document.querySelector('button');
// Add a click listener to the button, and insert
// the markup to the chosen element.
button.addEventListener('click', () => {
div.insertAdjacentHTML('beforeend', str);
});
<button>Click</button>
<div />

您可以将HTML附加到元素的innerHTML:

document.querySelector('button').addEventListener('click', function() {
document.body.innerHTML += `<div class='img-wrapper'> <img id='immagine_preview' width='200px' height='200px' data-id_immagine='1'><button type='button' class='rimuoviImg' ><span class='fa fa-times'></span></button></div>`;
})
<button>Insert HTML</button>

最新更新