未捕获的类型错误:对象#<HTMLDivElement>没有方法'绑定'

Uncaught TypeError: Object #<HTMLDivElement> has no method 'bind'

本文关键字:lt HTMLDivElement 绑定 有方法 gt 类型 错误 对象      更新时间:2023-09-26

我在网上搜索了解决方案。我试过使用"on"、"click",但不起作用。

var element = document.createElement( 'div' );
        element.className = 'element';
        element.style.backgroundColor = 'rgba(0,127,127,' + ( Math.random() * 0.5 + 0.25 ) + ')';
        element.style.cursor = 'pointer';
        element.bind("click", function(e){ alert("testing"); });

从上面的代码中,它将显示Uncaught TypeError: Object #<HTMLDivElement> has no method 'bind'。如果我将bind事件更改为element.click(function(){alert("testing")});,代码工作正常,但单击时不会显示警告框。

要添加事件侦听器,需要使用.addEventListener(),.bind()用于将自定义执行上下文传递给函数

element.addEventListener("click", function(e){ alert("testing"); });