Unobtrusive JavaScript 方法在 PAST 中是好的-特别是 HTML 中的事件处理程序绑定被认为是不好的做法(主要是因为 onclick events run in the global scope and may cause unexpected error提到了 意地绪语忍者)
但是..。
目前看来,这种方法似乎有点过时,需要一些更新。如果有人想成为专业的前端开发人员,编写大而复杂的应用程序,那么他就需要使用诸如 Angular、 Vue.js 等框架。.然而,框架通常使用(或允许使用) HTML 模板,其中事件处理程序直接绑定在 html 模板代码中,这非常方便、清晰和有效——例如,在角度模板中,人们通常会写:
给定一个 随心所欲字符串,如果你想构造一个内联处理程序,用这个字符串调用一个函数,对于通用解决方案,你必须转义 属性分隔符(与相关的 HTML 实体) ,还有你必须转义属性中字符串使用的分隔符,如下所示:
const str = prompt('What string to display on click?', 'foo\'"bar');
const escapedStr = str
// since the attribute value is going to be using " delimiters,
// replace "s with their corresponding HTML entity:
.replace(/"/g, '"')
// since the string literal inside the attribute is going to delimited with 's,
// escape 's:
.replace(/'/g, "\\'");
document.body.insertAdjacentHTML(
'beforeend',
'<button onclick="alert(\'' + escapedStr + '\')">click</button>'
);