[英]Adding Event Listeners in JavaScript
I have a JavaScript and divs defined using CSS3 classes. 我有一个使用CSS3类定义的JavaScript和div。 I need to add event listener to specific class div but it is not getting bound to it. 我需要将事件侦听器添加到特定的类div,但它没有绑定到它。
eg: 例如:
this._incrementEnabled = document.createElement('div');
this._incrementEnabled.className = this._incrementButtonProperties.enabledClass;
this.divElt.appendChild(this._incrementEnabled);
if (this.properties.incrementButtonConfig.enabled == null) {
this.properties.incrementButtonConfig.enabled = false;
}
this.setIncrementEnabled(this.properties.incrementButtonConfig.enabled);
this._incrementEnabled.addEventListener('click', this._incrementButtonProperties.incrementSelectCallback, false);
and the CSS: 和CSS:
.SchedMainCtrlIncrementBtn_En {
position: absolute;
top: 3px;
left: 240px;
display: inline-block;
font-size: 28px;
vertical-align: middle;
width: 35px;
height: 65px;
height: 35px;
background: url("../../../images/icons/IcnListAddRecipient_En.png") no-repeat center;
}
something like this: 像这样的东西:
var divs = document.querySelectorAll( 'div.yourclass' );
for( var i=0; i < divs.length; i++ ){
divs[ i ].addEventListener( 'eventname', callback, false );
}
EDIT: 编辑:
From reading your code with this very long variable names I conclude that you want to do something like this: 通过使用非常长的变量名读取代码,我得出结论,您想要执行以下操作:
this.element = document.createElement( 'div' );
this.element.className = 'someName';
this.parentElement.appendChild( this.element );
this.element.addEventListener( 'click', callback, false );
So if this.parentElement
is not defined, or if callback
is not defined it wont work. 因此,如果未定义this.parentElement
,或者未定义callback
它将无法正常工作。 I do not know how you coded the class, but all used functions ( document.createElement
, appendChild
, addEventListener
) are native functions, so they work. 我不知道您如何编码该类,但是所有使用的函数( document.createElement
, appendChild
和addEventListener
)都是本机函数,因此它们可以工作。
如果可能的话,尝试使用Jquery会更简单,您可以使用$('.class').click(function(){})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.