如何使javascript函数在html中工作



我有一个代码在js:

document.getElementById("collection").innerHTML = `
<div style="width: 100%; text-align: center" class="mb-4">
<h1>Collection of ${bottleData.length} bottles</h1>
</div>
${bottleData.map(bottleTemplate).join('')}
`

并希望有${bottleData.length}功能在HTML工作。HTML代码在这里:https://github.com/MarvelousMartin/absolut-vodka-collection/blob/master/index.html

有办法吗?谢谢。

在你的index.html文件中应该有一个事件监听器来使这个函数在html中工作。

假设你有一个按钮,想要一个函数工作,点击

HTML:

<button onclick="Test()">Event Listener in HTML</button>
<script src="Path_to_your_script_file"></script>

Js:

function Test() {
document.write("<h1>HTML code can be written Inside Js like this</h1>")
document.write("<h1>HTML can be written inside document.write('') in Js</h1>")
}

参见Codepen中的额外参考

最新更新