You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ID以lp-pom-button-开头的按钮绑定点击事件?

Solution for Targeting Buttons with Dynamic IDs

Absolutely, you can target all buttons whose IDs start with lp-pom-button- using JavaScript attribute selectors—this works just like SQL's LIKE 'lp-pom-button-%' pattern. Here's how to update your code to handle all such buttons:

<script type="text/javascript">
  // Get all buttons with IDs starting with "lp-pom-button-"
  const buttons = document.querySelectorAll('[id^="lp-pom-button-"]');
  
  // Add click event listener to each matching button
  buttons.forEach(button => {
    button.addEventListener('click', function(event) {
      ga(function() {
        const tracker = ga.getAll()[0];
        const clientId = tracker.get('clientId');
        document.getElementById('GACLIENTID').value = clientId;
        
        const userId = tracker.get('userId');
        document.getElementById('GAUSERID').value = userId;
      });
    });
  });
</script>

Key Changes Explained:

  • Attribute Selector: [id^="lp-pom-button-"] selects any element where the id attribute starts with the specified string. The ^= operator is the "starts with" match here, exactly what you need for your dynamic button IDs.
  • Loop Through Buttons: Using forEach ensures every matching button gets the click event listener, regardless of how many there are or what their suffix numbers are.
  • Preserved GA Logic: The core code to fetch clientId and userId from GA and populate the hidden fields remains unchanged—we're just expanding which buttons trigger this logic.

This approach is robust, works with any number of matching buttons, and handles the dynamic ID suffixes seamlessly.

内容的提问来源于stack exchange,提问作者jgeeda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:26:19