我有这个代码的问题:
var xButton = document.createElement("a");
xButton.className = "cXButton";
xButton.href = "#";
xButton.onclick = "closePanel()";
xButton.innerHTML = "X";
Run Code Online (Sandbox Code Playgroud)
虽然"closePanel()"是我已经写过的函数.我使用了Firebug,发现"onclick"属性没有出现在标签中.我看到一些线程,而不是函数的名称,它的实现(函数closePanel(){...}).这不是我想要的.
有什么建议怎么解决?
您的原始代码有两个问题:
"closePanel()" 是一个字符串.closePanel() 尝试(或者如果它不是字符串)调用该函数并将其输出分配给 xButton.onclick它应该是这样的:
xButton.onClick = closePanel;
Run Code Online (Sandbox Code Playgroud)
这将分配给函数的引用closePanel()来xButton.onClick,调用closePanel()时xButton.onClick被触发事件.
请记住,您可以this在声明中使用closePanel()以引用单击的元素.