[英]How do I pass additional parameters into an event
I have an array of clickable links "btns" 我有一系列可点击的链接“ btns”
for ( var i=0; i<btns.length; i++ ) {
btns[i].addEventListener('click', eventData, false);
eventData function is here: eventData函数在这里:
function eventData(e) {
dataLayer.push({
'event': 'home_cta',
'iteration': i, // HERE. I WANT TO ADD WHICH ELEMENT INDEX WITHIN THE FOR LOOP HERE
'gtm.element': e.target,
'gtm.elementClasses': e.target.className || '',
'gtm.elementId': e.target.id || '',
'gtm.elementTarget': e.target.target || '',
'gtm.elementUrl': e.target.href || e.target.action || '',
'gtm.originalEvent': e
});
I have two questions: 我有两个问题:
var somevar = "bla"
, how would I pass that to eventData within my for loop? var somevar = "bla"
,如何将其传递给我的for循环中的eventData? 'iteration'
property. 'iteration'
属性中对此进行了强调。 So I'd like to end up with a number between 1 and 6 for each iteration (Because variable "btns" has length 6). This would involve an IIFE (immediately invoked function expression): 这将涉及IIFE(立即调用的函数表达式):
for (var i = 0; i < btns.length; i++) {
(function(somevar, i) {
btns[i].addEventListener('click', function(e) {
eventData(e, somevar, i);
}, false);
})(somevar, i);
}
addEventListener
passes one argument and one argument only to its callback, so you have to "manually" call your eventData
function. addEventListener
将一个参数和一个参数传递给其回调,因此您必须“手动”调用eventData
函数。
(Note that without the (function() { ... })()
, each of the event listeners would have btns.length
passed to them as the value for i
.) (请注意,如果没有
(function() { ... })()
,则每个事件侦听器都会将btns.length
传递给它们,作为i
的值。)
To explain the IIFE a bit more, here's what you're basically doing: 为了进一步解释IIFE,这是您的基本操作:
var f = function(somevar, i) {
// ...
};
f(somevar, i);
That is, you're creating a function and immediately invoking it (hence the name). 也就是说,您正在创建一个函数并立即调用它(因此命名)。 Again, this is done so that the value of
i
(and somevar
if it changes) are kept the same for the appropriate iteration. 同样,这样做是为了使
i
的值(如果它改变, somevar
)对于适当的迭代保持相同。
You could also use .bind()
to "fixate" the first parameter of the bound function to the current index. 您还可以使用
.bind()
将绑定函数的第一个参数“固定”到当前索引。
for (var i=0; i<btns.length; i++ ) {
btns[i].addEventListener('click',
// <this> in the function will be the clicked button (as usual)
// but the first passed parameter would be the current iteration step <i>
eventData.bind(btns[i], i),
false);
}
function eventData(iteration, e) {
//...
'iteration': iteration,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.