如何为ID以lp-pom-button-开头的按钮绑定点击事件?
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 theidattribute 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
forEachensures 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
clientIdanduserIdfrom 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
相关产品推荐
相关产品推荐

