在JavaScript中调用模板文字内的onclick事件可以通过以下步骤实现:
<template id="myTemplate">
<button onclick="myFunction()">点击我</button>
</template>
const template = document.querySelector('#myTemplate');
const clone = template.content.cloneNode(true);
const button = clone.querySelector('button');
button.addEventListener('click', myFunction);
完整的示例代码如下:
<!DOCTYPE html>
<html>
<head>
<title>调用模板文字内的onclick事件</title>
</head>
<body>
<template id="myTemplate">
<button onclick="myFunction()">点击我</button>
</template>
<script>
function myFunction() {
alert('点击事件已触发!');
}
const template = document.querySelector('#myTemplate');
const clone = template.content.cloneNode(true);
const button = clone.querySelector('button');
button.addEventListener('click', myFunction);
document.body.appendChild(clone);
</script>
</body>
</html>
这样,当页面加载时,模板文字内的按钮将被克隆并添加到文档中,点击按钮时将触发myFunction函数。