gpt4 book ai didi

javascript - HTML5模板添加点击事件

转载 作者:行者123 更新时间:2023-11-28 01:55:24 26 4
gpt4 key购买 nike

如何向 html5 模板标签添加点击事件?

以下内容永远不会向图像注册点击事件:

<!doctype html>
<body>
<div id="content"></div>
<template id="itemTemplate">
foo
<img id='imageTag' src='image.png'>
</template>
<script>
var templ = document.querySelector('#itemTemplate');
templ.content.querySelector('#imageTag').click = function(){alert('xxxx');};
var content = document.querySelector('#content');
content.appendChild(templ.content.cloneNode(true));
</script>
</body>

最佳答案

我自己也遇到了同样的问题,我会将我所学到的写下来,以便其他人也能得到答案。

正如腺嘌呤评论的那样,不可能从模板内部做到这一点。我也尝试过。您可以做的就是完成模板创建,当所有元素都在 DOM 中注册后,您就可以添加事件监听器了。

所以你的代码将如下所示:

<!doctype html>
<body>
<div id="content"></div>
<template id="itemTemplate">
foo
<img id='imageTag' src='image.png'>
</template>
<script>
var templ = document.querySelector('#itemTemplate');
var content = document.querySelector('#content');
content.appendChild(templ.content.cloneNode(true));
document.querySelector('#imageTag').click = function(){alert('xxxx');};
</script>

当我需要向元素数组添加事件监听器(尝试动态构建分页器)时,我曾经遇到过同样的问题,因此我使用了 forEach 循环来为每个元素提供单击事件:

    for (var i = 0 ; i < totalPages ; i++) {
anchorElement.innerHTML = i + 1;
anchorElement.dataset.pageId = i + 1;
var clone = document.importNode(templateElement.content, true);
paginationContainer.appendChild(clone);
}

// Register pagination event listeners
document.querySelectorAll('.pagination a').forEach(function(anchorElement) {
$(anchorElement).on('click', function() {
alert('Hello');
});
});

关于javascript - HTML5模板添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19192022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com