我想在DOM元素上绑定AddEventListener纯javascript方法。 但是我使用包含html文件的AngularJS,这包括在AddEventListner函数绑定到DOM之后运行。所以纯JavaScript没有找到DOM。 我是纯JS字的新手。我使用了jQuery,但在这个项目中我只想使用AngularJS和纯JS。 :)
AngularJS
包含此代码(ng-include)<div class="col-xs-3 col-md-1 col-xs-offset-2 col-md-offset-0 padding-left-right-0">
<span class="game game-home" ng-show='gameEvent.game_home > 0' ng-click="addToSlip(gameEvent.id, gameEvent.name, gameEvent.game_home, 'H', gameEvent.number)" style="cursor: pointer;">
<span class="slip-game-event-add-button">
{{ gameEvent.game_home | number:2 }}
</span>
<span class="badge">{{ gameEvent.taken_home}}</span>
</span>
</div>
<div class="col-xs-3 col-md-1 padding-left-right-0">
<span class="game game-draw" ng-show='gameEvent.game_draw > 0'ng-click="addToSlip(gameEvent.id, gameEvent.name, gameEvent.game_draw, 'D', gameEvent.number)" style="cursor: pointer;">
<span class="slip-game-event-add-button">
{{ gameEvent.game_draw | number:2 }}
</span>
<span class="badge">{{ gameEvent.taken_draw}}</span>
</span>
</div>
<div class="col-xs-3 col-md-1 padding-left-right-0">
<span class="game game-away" ng-show='gameEvent.game_away > 0' ng-click="addToSlip(gameEvent.id, gameEvent.name, gameEvent.game_away, 'V', gameEvent.number)" style="cursor: pointer;">
<span class="slip-game-event-add-button">
{{ gameEvent.game_away | number:2 }}
</span>
<span class="badge">{{ gameEvent.taken_away}}</span>
</span>
</div>
这是我的纯javascript文件:
'For.the.view';
(function() {
var gameDom = document.getElementsByClassName("game");
for (var i=0;i<gameDom.length;i++) {
gameDom[i].addEventListener('click', clickEventForThis, false);
};
})();
function clickEventForThis(){
console.log("hello");
};
不幸的是,在AngularJS加载HTML文件之前,这个javascript代码会运行。所以它找不到任何gameDoms ......
是的,最简单的方法是使用“onclick
”attributate,但我认为这不是一个好的解决方案。
答案 0 :(得分:0)
您可以使用angular.ready事件:
angular.element(document).ready(function () {
var gameDom = document.getElementsByClassName("game");
for (var i=0;i<gameDom.length;i++) {
gameDom[i].addEventListener('click', clickEventForThis, false);
};
});