繁体   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