如何用jQuery在WordPress的Gravity Forms按钮上设置Google事件追踪
Hey, I get it—since Gravity Forms renders buttons dynamically (they aren’t present in the initial page HTML), your usual inline onclick approach won’t work here. The fix is using jQuery event delegation—this lets you attach a click handler to a parent element that exists when the page loads, which will catch clicks from any dynamically added child elements (like your "Rate it Now!" button).
Here’s a reliable, tailored solution:
1. Identify the Right Button Selector
Gravity Forms uses consistent CSS classes for its elements, so you can target your button accurately:
- Most submit buttons have the class
.gform_buttonor.gform_submit_button - If you only want to track this specific "Rate it Now!" button (not all Gravity Forms buttons), combine the class with a text selector to narrow it down.
2. Add the jQuery Code
Put this code in your WordPress site—you can use a custom JS file, enqueue it via your child theme’s functions.php, or use a plugin like Code Snippets to add custom JavaScript:
// Wait for the DOM to fully load before running code jQuery(document).ready(function($) { // Use event delegation on a stable parent (body works, but a closer container is more efficient) $('body').on('click', '.gform_button:contains("Rate it Now!")', function(e) { // Send the exact GA event you originally wanted ga('send', 'event', 'Rate it Now Form', 'Clicked'); // Optional: Log to browser console for quick testing console.log('GA event triggered: Rate it Now Form -> Clicked'); }); });
Breakdown of the Code:
$('body').on('click', '.gform_button:contains("Rate it Now!")', ...): This binds the click handler to the<body>(which exists on page load) and only triggers when the clicked element matches your specific button selector.- The
ga('send', ...)line is identical to your original inline code, so it will send the same event data to Google Analytics. - The
console.logline helps you verify the handler is working: just open your browser’s dev tools, click the button, and check the Console tab for the message.
3. For GA4 Users (Instead of Universal Analytics)
If your site uses Google Analytics 4 (gtag.js) instead of the older Universal Analytics (ga.js), replace the ga() line with this GA4-compatible code:
gtag('event', 'Clicked', { 'event_category': 'Rate it Now Form', 'event_label': 'Rate it Now Button' // Optional, but adds more context });
4. Test the Tracking
- Open your Google Analytics dashboard and go to Realtime > Events
- Click your Gravity Forms button on the front end of your site
- You should see the "Clicked" event under the "Rate it Now Form" category appear in realtime within a few seconds.
内容的提问来源于stack exchange,提问作者ajwerth

