作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的 html 页面中,我有一个按钮,单击时会创建另一个按钮。单击该创建的按钮会创建一个段落,但该按钮只能运行一次。我认为这是问题的原因,这是彼此内部的两个函数。更好的方法是什么?
将内部函数与包含函数分开编写会给我一个错误,因为在调用包含函数/单击原始按钮之前,内部函数尝试访问的 id 不存在。
// Containing function
document.getElementById("buttonCreator").onclick=function() {
targetElement.innerHTML = (""); // Reset the main divs contents
var button1 = document.createElement("button"); // Create a button
var bContent = document.createTextNode("Click me!");
button1.appendChild(bContent);
button1.setAttribute("id", "createdButton"); // Give the button an id
targetElement.appendChild(button1);
// Inner function - this only works once
document.getElementById("createdButton").onclick=function() {
targetElement.innerHTML = targetElement.innerHTML
+ "<br> <br>"
+ ("You clicked the created button!);
}
}
没有错误。
最佳答案
问题出在 targetElement.innerHTML = targetElement.innerHTML
中,您用新的 HTML 替换了附加了 DOM 事件(点击)的原始 HTML,并且不再附加该事件。
关于javascript - 另一个函数内部的函数只能运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595567/
有一条(相对)众所周知的 Perl 公理:“只有 Perl 可以解析 Perl”。我想知道 Perl 6 是否仍然如此? 扩大讨论...考虑到 PyPy 最近的更新,我想到了这个问题。 Perl 独特
这是设置。在上一个问题中,我发现我可以通过子组件中的状态传递对象属性,然后使用 componentDidUpdate 获取该对象属性。在这种情况下,状态和属性都称为到达。 这是基本代码... expo
我运行的是 10.5.2 社区版。我已经标记了 源/主要/资源 作为源目录。我可以右键单击并“编译”某些文件,据我所知,这意味着 IDE 将文件复制到与发送类文件的“com.mydomain.pack
我是一名优秀的程序员,十分优秀!