在网站的各个页面上,我通过 JavaScript 生成不同的点击处理程序,附加到特定页面元素的
innerHTML
中的链接。我用这样的实用函数来做到这一点:
function addClickLink(detail, detailHandler) {
element.innerHTML = `<a href="#" onclick="${detailHandler.name}(); return false;">Info about ${detail}</a>`
}
当
addClickLinkworks
是像 这样定义的函数时,调用
detailHandler
才有效
function heliumHandler () { ... }
addClickLinkworks("Helium", heliumHandler)
但当我使用匿名函数调用
addClickLinkworks
时则不然:
addClickLinkworks("Helium", function() { ... })
如何为匿名函数编写
"onclick"
字符串?
您可以包装该函数的字符串化版本,然后使用
(<stringified function source)()
调用它,以便 onclick
将其视为函数表达式(而不是语句):
function addClickLink(detail, detailHandler) {
element.innerHTML = `<a href="#" onclick="(${detailHandler})(); return false;">Info about ${detail}</a>`
}
// This works:
//function heliumHandler() { console.log('function declration'); }
//addClickLink("Helium", heliumHandler)
// And so does this:
addClickLink("Helium", function() { console.log('function expression'); })
<div id="element"></div>
但是,我不会建议这样做,而且我建议您创建一个 HTML 元素并向其添加侦听器,而不是这样做:
function addClickLink(detail, detailHandler) {
const anchor = document.createElement('a');
anchor.href = "#";
anchor.innerText = `Info about ${detail}`;
anchor.addEventListener("click", e => {
e.preventDefault(); // similar to return false in your previous `onclick`
detailHandler();
});
element.replaceChildren(anchor);
}
// This works:
// function heliumHandler() { console.log('function declration'); }
// addClickLink("Helium", heliumHandler)
// And so does this:
addClickLink("Helium", function() { console.log('function expression'); })
<div id="element"></div>