javascript - 如何在 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")
和"
都已'
用于在外部范围内进行引用。
该怎么办?
解决方案
删除内联处理程序(无论如何,它们通常被认为是非常糟糕的做法)并使用 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')">
});
推荐阅读
- apache-spark - PySpark 如何读取具有不同列的 csv 文件?
- python - Python-Pandas:如何在原地更改 df 时避免 keyerror
- html - 如何隐藏与下拉选择不匹配的图像
- javascript - 如何在 React js 中将文本转为语音
- node.js - 使用 OAuth2 令牌访问 O365 Microsoft Outlook 帐户,以在 Nodejs 中读取/删除电子邮件
- html - 如何缩放 iframe?
- react-native - Mapview 区域道具使地图变慢并挂起代替使用的东西(请帮助我)
- hadoop - hql的mr任务无法提交到hadoop集群,出现超时错误
- suitescript - 在suitescript中导入csv时不创建记录
- ios - 运行本机 ios 应用程序时出现以下错误