[英]Want to make an empty <div> element clickable via JavaScript (no jQuery)
我試圖通過單獨使用HTML和Javascript使兩個空的<div>
元素可點擊。 沒有jQuery。 我有這個HTML文件...
<!DOCTYPE html>
<html>
<head>
<title>whatever</title>
<link rel="stylesheet" href="css_squares" media="screen" >
<script src="lala.js"></script>
</head>
<body>
<h1>Clickable Squares</h1>
<div id="top_square" onclick="alert('Top square clicked')">
</div>
<div id="bottom_square">
</div>
</body>
</html>
還有這個簡單的CSS ...
#top_square {
width: 50px;
height: 50px;
background-color: #01FF55;
}
#bottom_square {
width: 150px;
height: 150px;
background-color: #AB877F;
}
我想使兩個方塊在單擊時創建一個警報框。 頂部方框已經通過HTML代碼實現了這一點,但是我無法通過Java代碼獲得底部方框來創建類似的警報。 這就是我嘗試過的...
window.onload = init;
function init() {
alert("you have successfully loaded an external .js file.");
// this is just to check that lala.js is loading.
var bottom_sqr = getElementById("bottom_square");
// I also tried calling 'document.getElementById'...
bottom_sqr.onclick = handle_bottom_click;
function handle_bottom_click() {
alert('Bottom square clicked');
}
這根本不起作用...因此該職位顯然。 任何幫助將不勝感激。
您缺少init方法的右括號,是的,在那里需要document
。 window
是javascript的全局對象,不存在window.getElementById
方法:
function init() {
alert("you have successfully loaded an external .js file.");
// this is just to check that lala.js is loading.
var bottom_sqr = document.getElementById("bottom_square"); // document is required here
bottom_sqr.addEventListener('click', handle_bottom_click);
function handle_bottom_click() {
alert('Bottom square clicked');
}
}
由於默認情況下HTMLElement不可“單擊”,因此您需要將事件監聽器附加到addEventListener
而不是僅附加element.onclick
。
編輯:顯然element.onclick
是有效的,因為onclick
是全局事件處理程序 。
此代碼有效
var v = document.getElementById("bottom_square");
v.onclick = function(){
alert("Bottom square clicked");
};
的jsfiddle鏈接- https://jsfiddle.net/41Ljp1w7/
您代碼中的問題是,除了缺少init方法和文檔選擇器中的右括號之外,您在調用函數時也沒有使用第一個括號,即“ window.onload = init;” 而不是“ window.onload = init()”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.