我想创建一个图像元素,单击该元素会打开一个具有指定背景的空白浏览器窗口:
<img src="http://example/image1.jpg" onclick="var w=window.open('','_blank');w.document.body.style.backgroundColor='url("http://example/image2.jpg")'">
但是,我无法使用 "
、'
或 \xXX
(十六进制)作为 url 来实现上述功能("http://example/image1.jpg")
,因为 "
和 '
都已用于外部作用域中的引用。
该怎么办?
最佳答案
删除内联处理程序(无论如何,它们通常被认为是非常糟糕的做法)并使用 Javascript 正确添加监听器,您不必担心由于 HTML 标记而必须转义:
const img = document.querySelector('img'); // feel free to make this more precise as needed
img.addEventListener('click', () => {
var w = window.open('','_blank');
w.document.body.style.backgroundColor = 'url("http://example/image2.jpg")';
// alert('HelloWorld')">
});
关于javascript - 如何在 HTML 元素的 JS 事件监听器中嵌套引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57521403/