如何从 PHP 添加第二个点击操作

how to add second onclick action from php

本文关键字:操作 第二个 添加 PHP      更新时间:2023-09-26

我在php代码中有这一行:

$return .= '            <div class="acrDivP" onClick="javascript: window.location.href = ''' . $productUrl . ''';" id="acrLink">' . $resultText . '</div>';

我想添加第二个 onClick 操作,如下所示的粗体 (**):

$return .= '            <div class="acrDivP" onClick="javascript: window.location.href = ''' . $productUrl . ''';**ga('send', 'event', 'testEvent', 'click', 'ProductName');**" id="acrLink">' . $resultText . '</div>';

我知道我的语法大错特错,因为必须转义一些字符。有人可以帮我修复语法吗?还是我需要一种全新的方法?

$return .= '            <div class="acrDivP" onClick="javascript: ga(''send'', ''event'', ''testEvent'', ''click'', ''ProductName''); window.location.href = ''' . $productUrl . ''';" id="acrLink">' . $resultText . '</div>';

你可以这样做,只是需要很多粗糙的逃逸。这会降低代码的可读性和可维护性。

$return .= '<div class="acrDivP" onClick="window.location.href = ''' . $productUrl . '''; ga(''send'', ''event'', ''testEvent'', ''click'', ''ProductName'');" id="acrLink">' . $resultText . '</div>';

这需要一些重构,但是如果你能为代码打破PHP,它会更干净:

<div class="acrDivP" onClick="window.location.href = '<?php echo $productUrl ?>'; ga('send', 'event', 'testEvent', 'click', 'ProductName');" id="acrLink"><?php echo $resultText ?></div>