我正在尝试创建一个脚本,其中会触发多个事件,并根据页面上显示的广告将其发送到Google Analytics。到目前为止,我提出了这个,但只有第一个,领导板横幅正在工作,而其余的没有。我确信我的代码可以简化,因为我不是jquery的专家,但问题是事件,因为点击事件都不起作用。当我包含一个用于调试的警报时,这会被解雇,所以不确定我的代码是否有问题。
<!-- Tracking -->
<script>
jQuery(document).ready(function($) {
//leaderboard
$(".ad_leaderboard").ready(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_leaderboard_term']; ?>', 'view', '<?php echo $GLOBALS['ad_leaderboard_title']; ?>');
});
$(".ad_leaderboard").click(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_leaderboard_term']; ?>', 'click', '<?php echo $GLOBALS['ad_leaderboard_title']; ?>');
});
//medium-rectangle
$(".ad_medium_rectangle").ready(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_medium_rectangle_term']; ?>', 'view', '<?php echo $GLOBALS['ad_medium_rectangle_title']; ?>');
});
$(".ad_medium_rectangle").click(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_medium_rectangle_term']; ?>', 'click', '<?php echo $GLOBALS['ad_medium_rectangle_title']; ?>');
});
//skyscraper
$(".ad_skyscraper").ready(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_skyscraper_term']; ?>', 'view', '<?php echo $GLOBALS['ad_skyscraper_title']; ?>');
});
$(".ad_skyscraper").click(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_skyscraper_term']; ?>', 'click', '<?php echo $GLOBALS['ad_skyscraper_title']; ?>');
});
//halfbanner
$(".ad_halfbanner").ready(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_halfbanner_term']; ?>', 'view', '<?php echo $GLOBALS['ad_halfbanner_title']; ?>');
});
$(".ad_halfbanner").click(function() {
ga('send', 'event', '<?php echo $GLOBALS['ad_halfbanner_term']; ?>', 'click', '<?php echo $GLOBALS['ad_halfbanner_title']; ?>');
});
});
</script>
答案 0 :(得分:1)
您可以使用.on()将函数绑定到多个事件,但不能将php变量用于动态事件。因为PHP是服务器端而jQuery是客户端。您需要先收集PHP数据。
var ad_data_term = {
ad_leaderboard:"<?php echo $GLOBALS['ad_leaderboard_term']; ?>",
ad_medium_rectangle:"<?php echo $GLOBALS['ad_medium_rectangle_term']; ?>",
ad_skyscraper:"<?php echo $GLOBALS['ad_skyscraper_term']; ?>",
ad_halfbanner:"<?php echo $GLOBALS['ad_halfbanner_term']; ?>"
};
var ad_data_title = {
ad_leaderboard:"<?php echo $GLOBALS['ad_leaderboard_title']; ?>",
ad_medium_rectangle:"<?php echo $GLOBALS['ad_medium_rectangle_title']; ?>",
ad_skyscraper:"<?php echo $GLOBALS['ad_skyscraper_title']; ?>",
ad_halfbanner:"<?php echo $GLOBALS['ad_halfbanner_title']; ?>"
};
$(".ad_leaderboard, .ad_medium_rectangle, .ad_skyscraper, .ad_halfbanner").on('ready click', function() {
var myClass = $(this).attr("class");
ga('send', 'event', ad_data_term[myClass], 'view', ad_data_title[myClass]);
});
希望这有助于:)
答案 1 :(得分:0)
没关系我已经完成了以下操作,但是如果你能帮我简化那就太棒了:P
if ($('.ad_leaderboard').length && $('.ad_leaderboard').css('display') != 'none')
{
var viewClass = $(".ad_leaderboard").attr("class");
alert(ad_data_title[viewClass]);
ga('send', 'event', ad_data_term[viewClass], 'view', ad_data_title[viewClass]);
}