繁体   English   中英

dataLayer.push 重复

[英]dataLayer.push duplicated

我正在尝试推送数据层。 但它一直给我一个重复的数组。 请看下面我的代码

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>

 dataLayer = [{
 'productID': '123456',
 'productTitle': 'Very awesome product',
 'productPrice': '13.00'
 }];
function next_step1c() {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
     'event': 'Enquiry',
     'PageURL': window.location.href,

     });
}
</script>
<fieldset id="firstc">
          <div class="funkyradio">
            <div class="funkyradio-success" onclick="next_step1c()">
                <input type="radio" name="buy" id="check1c" value="Rolex"/>
                <label for="check1c">Rolex</label>
            </div>
          </div>
</fieldset>

当我单击单选按钮时,我得到以下结果。 在此处输入图片说明

但是当我点击劳力士这个词时。 我得到重复

在此处输入图片说明

怎样才能一键点击劳力士这个词?

像这样尝试。 您将 onclick 添加到.funkyradio-success类。 因此,当您clicked单选按钮时,它只能工作1次。 但是当你点击标签按钮时,它会clicks double 因为当您click label时,就会出现.funkyradio-success onclick。 并且label binded to radio input因此input click trigger可以工作。 所以你的函数调用了2次。

 dataLayer = [{ 'productID': '123456', 'productTitle': 'Very awesome product', 'productPrice': '13.00' }]; function next_step1c() { console.log('you clicked me'); window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'event': 'Enquiry', 'PageURL': window.location.href, }); }
 <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <fieldset id="firstc"> <div class="funkyradio"> <div class="funkyradio-success" onclick="next_step1c()"> <input type="radio" name="buy" id="check1c" value="Rolex"/> <label for="check1c">Rolex</label> </div> </div> </fieldset>

添加 onclick 以输入收音机

 dataLayer = [{ 'productID': '123456', 'productTitle': 'Very awesome product', 'productPrice': '13.00' }]; function next_step1c() { console.log('you clicked me'); window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'event': 'Enquiry', 'PageURL': window.location.href, }); }
 <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <fieldset id="firstc"> <div class="funkyradio"> <div class="funkyradio-success" > <input type="radio" name="buy" id="check1c" onclick="next_step1c()" value="Rolex"/> <label for="check1c">Rolex</label> </div> </div> </fieldset>

只需使用.onchange代替无线电类型的输入元素,我认为检查是否定义了 dataLayer 没有任何意义,因为它始终在此代码中,并且避免编写内联 JS,因为它有很多缺点。

 var dataLayer = [{ 'productID': '123456', 'productTitle': 'Very awesome product', 'productPrice': '13.00' }]; document.querySelector("#check1c").onchange = function () { dataLayer.push({ 'event': 'Enquiry', 'PageURL': window.location.href, }); console.log(dataLayer); };
 <fieldset id="firstc"> <div class="funkyradio"> <div class="funkyradio-success"> <input type="radio" name="buy" id="check1c" value="Rolex"/> <label for="check1c">Rolex</label> </div> </div> </fieldset>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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