簡體   English   中英

如何僅使用JavaScript定義按鈕元素的onclick屬性?

[英]How do I define a button element's onclick attribute using just JavaScript?

就像標題中所說的那樣,我試圖在JavaScript中創建一個button元素,但是當我嘗試設置其onclick屬性時,它只會忽略它。 我在本網站(例如this )上也查看了與此主題相關的其他問題,但是每個人都回答將其放入HTML中,例如:

<button id="buttonid" onclick="click(this);">

但是我的程序完全使用JavaScript動態創建HTML按鈕(它們在表格上對齊,因此使用for循環非常有用。此外,我對JavaScript更加熟悉)。 像這樣:

var b = document.createElement("button");
b.id = "buttonid";
b.onClick = "click(this);"; //I've tried many variations with no success
document.appendChild(b);

在HTML中永遠不會聲明button元素。 我需要一種單獨使用JavaScript添加onclick屬性的方法。 我對JQuery不太了解,所以我更喜歡JavaScript。

先感謝您。

PS,我已經嘗試過使用小寫.onclick和camelcase .onClick的以下所有方法:

b.onClick = "click(this);"; //just simply doesn't work
b.onClick = click(this);    //actually runs the program there, with some ambiguous "this" object
b.onClick = click;          //passes the actual function, but disallows the ability to pass the button's object (via "this")

嘗試這個

  var b = document.createElement("button"); b.onClick = function(){ alert("on click handler"); }; 

您可以使用的addEventListener到監聽器添加到按鈕並綁定到通過按鈕this對於處理函數。

b.addEventListener(`click`, click.bind(b));

或者,如果您想使用onClick ,只需使用bind

b.onClick = click.bind(b);

試試b.onClick = function(){console.log(“ test”); }

我不確定您的“點擊”功能是什么。 也許它尚未被聲明。 或正在發生的事情是您的函數名為click“ function click(){...}”,而需要單擊= function(){...}


 (function(){ // create the button var buttonB = document.createElement('button'); buttonB.id = 'buttonB'; var textB = document.createTextNode('Button B'); buttonB.appendChild( textB ); // set the click event on the button buttonB.addEventListener('click', function(){ // console.log('test'); // console.log( this ); clickFunc( this ); }); // populate the DOM-body with the button document.body.appendChild( buttonB ); })(); function clickFunc( that ){ console.log( that ); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM