I have an array of clickable links "btns"
for ( var i=0; i<btns.length; i++ ) {
btns[i].addEventListener('click', eventData, false);
eventData function is here:
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? 'iteration'
property. So I'd like to end up with a number between 1 and 6 for each iteration (Because variable "btns" has length 6). How would I do that? This would involve an IIFE (immediately invoked function expression):
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.
(Note that without the (function() { ... })()
, each of the event listeners would have btns.length
passed to them as the value for i
.)
To explain the IIFE a bit more, here's what you're basically doing:
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.
You could also use .bind()
to "fixate" the first parameter of the bound function to the current index.
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,
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.