Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript代码既不能在HTML代码中的脚本标记内工作,也不能在外部JS文件中工作_Javascript_Html - Fatal编程技术网

JavaScript代码既不能在HTML代码中的脚本标记内工作,也不能在外部JS文件中工作

JavaScript代码既不能在HTML代码中的脚本标记内工作,也不能在外部JS文件中工作,javascript,html,Javascript,Html,下面是我的HTML代码,标记中的javascript部分不起作用。即使我将JavaScript代码粘贴到外部JS文件-script.JS,它也不起作用。我试着像这样在script.js中单独编写,但这对我也不起作用:- document.getElementById(“.button”).addEventListener(“单击”,函数(){ document.querySelector(“.popup”).style.display=“flex”;}); document.getElement

下面是我的HTML代码,标记中的javascript部分不起作用。即使我将JavaScript代码粘贴到外部JS文件-script.JS,它也不起作用。我试着像这样在script.js中单独编写,但这对我也不起作用:-

document.getElementById(“.button”).addEventListener(“单击”,函数(){
document.querySelector(“.popup”).style.display=“flex”;});
document.getElementById(“.close”).addEventListener(“单击”,函数(){
document.querySelector(“.popup”).style.display=“无”;});
下面是用脚本标记编写的HTML代码和JavaScript代码


用于添加/编辑专业知识详细信息的弹出窗口
专业领域:


经验:
月份数: 年数:

费率 远程:
每小时> 每主题选项> 每章选项> 金额(卢比): 中心:
每周选项> 每月> 金额(卢比): 学员位置:
每类选项> 每小时> 金额(卢比):
我的位置:
每类选项> 每小时> 金额(卢比):

document.getElementById(“.button”).addEventListener(“单击”,函数(){ document.querySelector(“.popup”).style.display=“flex”; }); document.getElementById(“.close”).addEventListener(“单击”,函数(){ document.querySelector(“.popup”).style.display=“无”; });
您确定js文件的路径正确吗?
其次,您是否尝试插入阻止默认事件以阻止正常的单击功能?否则,代码的所有其他部分都无法启动。
文档。getElementById()
方法仅通过元素的
id
-属性获取元素。因此,对“.button”和“.close”元素使用
document.querySelector()
方法,例如:

document.querySelector(“.button”).addEventListener(“单击”,函数(){
document.querySelector(“.popup”).style.display=“flex”;
});
document.querySelector(“.close”).addEventListener(“单击”,函数(){
document.querySelector(“.popup”).style.display=“无”;
});

这是因为您在编写javascript代码时出错了

您正在将类名
.button
传递给
getElementById()
方法。将其替换为
querySelector()
方法。像这样:-

document.querySelect(".button").addEventListener("click", function(){
       document.querySelector(".popup").style.display = "flex";});
document.querySelector(".close").addEventListener("click", function(){
       document.querySelector(".popup").style.display="none";});

您处理的是一个类,而不是一个id。您可以在html代码中将“类”更改为“id”,这样您就不会再有任何问题了

或者你可以用

getElementsByClassName('.button')[0].addEventListener
而是在脚本中


这两个选项中的任何一个都可以解决您的问题

请等待,直到您有足够的代表发表评论;不要用答案来回答这个问题。“不起作用”不是一个很好的bug报告。你能解释一下你认为应该发生的事情吗?你的代码中有一个语法错误
getElementById
获取元素的ID属性的值。代码中没有ID为“.button”或“button”的元素。另外请注意,您的选项元素被错误地关闭
选项>
是无效的HTML。噢,非常感谢!当我使用querySelector而不是getElementByID()Perfect+1时,它起作用了。在添加事件侦听器之前,您应该检查元素是否为null。:)