简体   繁体   English

将 html 元素添加到 EventListener 屁股回调函数中

[英]adding html elements into EventListener ass callback function

I have a button where I want to add some data, from a file, into an event listener as a callback function我有一个按钮,我想将文件中的一些数据作为回调函数添加到事件侦听器中

function jokesFunc(){
const allJokes = jokes.getJokes().map(joke => "<li>"+joke+"</li>");
document.getElementById("jokes").innerHTML = allJokes.join("");
};


document.getElementById("container").addEventListener('click', jokesFunc)

here I have made a callback function, that is supposed to show jokes, whenever a button is clicked, but it says:在这里我做了一个回调函数,它应该在点击按钮时显示笑话,但它说:

 Cannot read property 'addEventListener' of null

even tough I have an element with an id of the container in my HTML code即使很难,我的 HTML 代码中有一个带有容器 ID 的元素

I have made a function, that adds "jokes" elements in the my "container" div, whenever it is clicked, but since it is an anonymous function, how can I pass in the callback function?我做了一个函数,它在我的“容器”div 中添加“笑话”元素,每当它被点击时,但由于它是一个匿名函数,我如何传入回调函数?

If you are so sure that there is a #container in the document, then, this is a subtle problem.如果您确定文档中存在#container,那么这是一个微妙的问题。 Please I have no solution but guide that can help you to figure out what is happening.请我没有解决方案,但可以帮助您弄清楚发生了什么的指南。 (1) Check if any other id can be sellected with all your code (2) Comment out all your code and check if you can select an id and addEventListener to it. (1) 检查是否有任何其他 id 可以与您的所有代码一起出售 (2) 注释掉您的所有代码并检查您是否可以选择一个 id 并为其添加事件监听器。 Note that if you added an eventlistener to an element that is not available during page load, js will throw error.请注意,如果您将事件侦听器添加到页面加载期间不可用的元素,则 js 将抛出错误。 Check if the constant allJokes has value by step running the file (inspect it)通过运行文件检查常量 allJokes 是否具有值(检查它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM