为什么js放在head部分没有反应,必须放在body部分下才会起作用。贴上代码。。

<title>无标题文档</title>
<style>
.button {
display: inline-block;
padding: 4px 10px;
border: 2px solid #cacaca;
background-color: #eee;
border-radius: 3px;
color: #333;
cursor: pointer;
}
.button:focus { outline: 1px dashed #34538b;}
</style>

</head>

<body>
<span class="button">按钮1</span>
<span class="button" role="button" tabindex="0">按钮2</span>
<span class="button" data-key="true" role="button" tabindex="0">按钮3</span>
<a class="button" href="javascript:">按钮4</a>
<script src="http://img3.douban.com/js/packed_jquery.min6301986802.js"></script>//为什么要放在body内容中,放于head部分没有作用呢。。。
<script>
$(".button").each(function() {
$(this).bind("click", function() {
alert("啊~我被点击了!");
});
if ($(this).attr("data-key")) {
$(this).bind("keydown", function(e) {
var code = e.which;
// 13 = 回车, 32 = 空格
if (code === 13 || code === 32) {
$(this).trigger("click");
}
});
}
});
</script>
</body>

js执行顺序问题,script标签写在上边的先执行,所以你的代码要放到你引入jquery的后边,同时你这样写的话,你的js是先执行的,但是你的button这时候还不存在,你放到后边,前面的html加载完js就能找到了
如果你非要放在head里的话,把你的代码放到window.onload里边
window.onload=function(){
你的js代码
}
或者用jquery的
$(document).ready(function(){
你的js代码
})
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答