【发布时间】:2022-10-23 21:24:57
【问题描述】:
我想动态地将onClick 属性添加到图像中。但是点击事件不起作用。
//Code
const parser = new DOMParser();
const doc = parser.parseFromString(htmlContent,
"text/html"
);
const imageData = doc.querySelectorAll("img");
imageData.forEach((x: any) => {
htmlContent = htmlContent.replace(
x.outerHTML,
'<img width="240" height="160" style="cursor: grab; margin: 10px;" src="' +
x.getAttribute("src") + '"onClick={() => setOpen(true)}/>'
);
});
试过了,
onClick={handleClick(true)}
const handleClick = (flag: boolean) => {
setOpen(flag)
}
onClick={setOpen(true)}
onClick={() => ' +setOpen(true) + '}
x.addEventListener('onClick', () => setOpen(true));
html内容:
<p>new test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468977463_0"></p><p>new new test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468986873_0"></p><p>next level test <img src="https://i.imgur.com/7KpCS0Y.jpg%22" width="100" height="100" id="img_1665468996237_0"></p><p></p><p>format test</p><ol><li><p>one</p></li><li><p>two </p></li><li><p>three</p></li></ol>
我能得到任何帮助吗?
【问题讨论】:
-
你循环的 imageData 是什么?您可以添加实际 html 内容的示例吗?
-
@SiddharthSathe 更新了问题,请检查
标签: javascript reactjs typescript