问题
I am working with jQuery code created by someone else, and I am very new to jQuery (fair warning).
I need to add google event tags to the links the jQuery is creating. This jQuery is for a modal pop up that contains icons for various sizes of an item, and a static button. When the user hovers over the icon, the link on the button changes, and I need to add google analytics tagging to the link for each icon when it changes on the button.
Here is the code that creates the link for the button when a particular icon is hovered over:
$('#modal_sizes_4 .size_5').hover(function() {
if (!$(this).hasClass('selected')) {
$('#modal_sizes_4 .selected').removeClass('selected');
$(this).addClass('selected');
$('#modal_sizes_4 .detail_left h3').text('15 3/4” Item');
$('#modal_sizes_4 .detail_left p').text('Good for many things.');
$('#modal_sizes_4 .detail_right img').attr({
src: 'images/5.4.5-product.jpg'
});
$('#modal_sizes_4 .detail_bottom a.shop_size').attr({
href: 'http://testing.com'
});
}
});
What is the best way to add this to the link once it's created:
onclick = "_gaq.push(['_trackEvent','CIGuide', 'Click Shop Size', '15 3/4 Item']);" >
I have tried using .click, .attr, .on and .bind with no luck.
I apologize if my question doesn't make perfect sense, again, I am very new to all of this. Any help would be appreciated. What I am ultimately trying to achieve is an event tag in google. Thank you.
回答1:
You can use the following code to add the call:
$( "#my_element a" ).bind( "mousedown" , function() {
_gaq.push( [ "_trackEvent" , "CIGuide" , "Click Shop Size" , "15 3/4 Item" ] ) ;
} ) ;
The code above will work for any anchor under the element whose id is "my_element":
<h1>Hello World</h1>
<div id="my_element">
<h2>Title here</h2>
<ul>
<li>
<a href="http://www.example.com">Example</a>
</li>
<li>
<a href="./some-page.html">Some Page</a>
</li>
<li>
<a href="http://www.anotherexample.com">Another Example</a>
</li>
</ul>
</div>
<a href="./wont-fire">This link won't fire the event</a>
Customize the selector to fit your purposes and that's it.
来源:https://stackoverflow.com/questions/13844292/not-able-to-successfully-add-google-analytics-event-tag-to-link-created-by-attr