我对JS和jQuery
都很陌生,我正试图制作使用它们的字幕播放器。不幸的是,我很早就陷入了困境。
当我尝试通过.js文件选择一些HTML
元素时,它就像找不到我要求的元素一样,并且没有任何反应。如果我尝试提醒元素的值或HTML,则会提醒undefined
。
所以这就是代码:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="jquery-2.1.3.min.js"></script>
<script src="script.js"></script>
<style type="text/css">
body{
margin: 0px;
padding: 0px;
}
#wrapper{
width: 150px;
text-align: center;
background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,#75bdd1), color-stop(14%,#75bdd1), color-stop(100%,#2294b3));
padding: 10px 2px;
}
h3{
font-family: Arial, Helvetica, sans-serif;
}
img{
width: 50px;
margin: 0 auto;
}
input{
display: none;
}
</style>
</head>
<body>
<div id="wrapper">
<h3>Select subtitles file</h3>
<img src="browse.png" alt="browse">
</div>
<input type="file" accept=".srt" id="file">
</body>
</html>
的script.js
$("div").click(function () {
console.log('loaded');
});
感谢。
答案 0 :(得分:9)
由于您的script
标记 上面定义了它所依赖的元素的HTML,因此无法找到它们,因为它们在该代码运行时不存在。以下是页面中发生事情的顺序:
html
和head
元素meta
元素,解析器注明其内容script
元素script
元素div
个元素如何纠正它:
将script
元素移到最后,就在结束</body>
标记之前,因此在代码运行之前所有元素都存在。除非有充分的理由不这样做,这通常是最好的解决方案。
使用jQuery的ready
feature。
在脚本元素上使用defer
attribute,但要注意并非所有浏览器都支持它。
但同样,如果您控制脚本元素的去向,#1通常是您最好的选择。
答案 1 :(得分:2)
当你调用.click()方法时,dom没有完全加载。 你必须等到DOM中的所有内容都被加载。所以你必须将你的script.js更改为:
$(document).ready(function(){
$("div").click(function () {
console.log('loaded');
});
});
答案 2 :(得分:1)
您应该在DOM Ready事件之后执行脚本。在jquery中它是如此:
$(function(){
$("div").click(function () {
console.log('loaded');
})
});
答案 3 :(得分:0)
$(document).on('click', "element" , function (ev) {
console.log('loaded');
})
})