我如何修复JavaScript中的引号?

问题描述 投票:0回答:3

我的JavaScript是这样的:

var contentItem = '<a onclick="ga('send', 'event', 'find-a-doctor', 'appointment', 'Appointment from Home');" class="waves-effect waves-dark">Make an Appointment</a>';

上面的引号似乎是错误的。我该如何解决?

javascript jquery click
3个回答
1
投票

您可以使用``(反引号或反引号),例如

var contentItem = `<a onclick="ga('send', 'event', 'find-a-doctor', 'appointment', 'Appointment from Home');" class="waves-effect waves-dark">Make an Appointment</a>`;

0
投票

内联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');
}
© www.soinside.com 2019 - 2024. All rights reserved.