简体   繁体   中英

Return Value from addEventListener - JS

I am working around existing code here. I have multiple divs with a product id attribute. Nested deep in each div is a button. When that button is clicked I need to pull the product id of the div it's nested in.

I have come up with some code that will locate that data, but am struggling to return that data as a value. Any guidance or easy-to-understand literature would be appreciated.

<!-- HTML -->
<div product-id="111">
    <div>
        <a class="button" href="#">Button A</a>
    </div>
</div>

<div product-id="222">
    <div>
        <a class="button" href="#">Button B</a>
    </div>
</div>

// Javascript
document.querySelectorAll(".button").forEach(function(e){
    e.addEventListener("click", grab_id);
});

function grab_id() {
    var prod_id = this.closest("div[product-id]").getAttribute("product-id");
    console.log(prod_id);
}

This is for creating a variable in Google Tag Manager. They let you use JS to do what is necessary to pull that data. But returning the value is my issue. Here is a snap shot of Google's tool Tip on the matter. 在此处输入图片说明

I prefer this way, because it' s more scalable. For example if you want to track other buttons/ elements inside this div.

1) Create Javascript variable in GTM which will find and return product ID for you.

Code:

function() {
    var el = {{Click Element}}
    while (el.getAttribute("product-id") == null && el !=null) {
      console.log(el);
      console.log(el.getAttribute("product-id"));
        el = el.parentElement
    }
    return el != null ? el.getAttribute("product-id") : "";
}

在此处输入图片说明

2) Create a trigger in GTM which will fire when you click to the button

Trigger type: Click - Just Links

This trigger fires on: Click Element matches CSS selector .button

在此处输入图片说明

3) Create a tag which you want to send. In my example i will use GA Event

Just use variable {{Product ID}} which will contains your product id

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM