我正在尝试使用 javascript 创建一个具有 onclick 事件的按钮,该事件调用在 head 中定义的函数,该函数接受相对于按钮的 dom 对象作为参数。我该怎么做?
例如:
<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>
javascript:
var newButton = document.createElement("button");
???
最后我希望新按钮与现有按钮相同。
function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "im a button";
button.onclick = func;
context.appendChild(button);
}
window.onload = function() {
createButton(document.body, function() {
highlight(this.parentNode.childNodes[1]);
// Example of different context, copied function etc
// createButton(this.parentNode, this.onclick);
});
};
这就是你想要的吗?
您还可以使用内置的 setAttrbute javascript 函数。
var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")
希望对你有帮助
var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")