我的JavaScript是这样的:
var contentItem = '<a onclick="ga('send', 'event', 'find-a-doctor', 'appointment', 'Appointment from Home');" class="waves-effect waves-dark">Make an Appointment</a>';
上面的引号似乎是错误的。我该如何解决?
您可以使用``
(反引号或反引号),例如:
var contentItem = `<a onclick="ga('send', 'event', 'find-a-doctor', 'appointment', 'Appointment from Home');" class="waves-effect waves-dark">Make an Appointment</a>`;
内联JS会引起各种问题。相反,您可以采用现代方法并使用事件侦听器:
// Create your item and add it to the page
var contentItem = '<a class="waves-effect waves-dark">Make an Appointment</a>';
document.body.insertAdjacentHTML('beforeend', contentItem);
// Cache the element you added and add an event listener to it
// that calls handleClick when clicked
const wavesEffect = document.querySelector('.waves-effect');
wavesEffect.addEventListener('click', handleClick, false);
// Now your call to `ga` is much cleaner
function handleClick(e) {
ga('send', 'event', 'find-a-doctor', 'appointment', 'Appointment from Home');
}