首页 > 解决方案 > 如何在 HTML 元素的 JS 事件监听器中嵌套引号?

问题描述

我想创建一个图像元素,单击该元素时会打开一个具有指定背景的空白浏览器窗口:

<img src="http://example/image1.jpg" onclick="var w=window.open('','_blank');w.document.body.style.backgroundColor='url("http://example/image2.jpg")'">

但是,我无法使用 , 或 (hex) for 来完成上述操作"'因为\xXX两者url("http://example/image1.jpg")"都已'用于在外部范围内进行引用。

该怎么办?

标签: javascripthtmlweb

解决方案


删除内联处理程序(无论如何,它们通常被认为是非常糟糕的做法)并使用 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')">
});

推荐阅读