16

私はjavascriptを使用して、ボタンに関連するdomオブジェクトをパラメーターとして取り込むヘッドで定義された関数を呼び出すonclickイベントを持つボタンを作成しようとしています。どうすればこれを行うことができますか?

元:

<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");
???

結局、新しいボタンを既存のボタンと同じにしたいのです。

4

2 に答える 2

38
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);
    });
};

それはあなたが望むものですか?

于 2011-12-28T01:38:29.933 に答える
0

組み込みのsetAttrbutejavascript関数を使用することもできます。

var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")

それが役立つことを願っています

于 2020-07-04T13:07:48.543 に答える