這裏發生了一些奇怪的事情。document.getElementById在動態創建的div上返回null
我的網站使用JavaScript創建動態div,但儘管它們被輸入到DOM(至少這是我認爲的),但在調用div時返回null。
這是其上裝載javscript代碼之前
</body>
function AddPlayer(){
var name = document.getElementById('name').value;
createBox(name);
};
function createBox(name){
var span = document.createElement('span');
span.id = name;
span.innerHTML = name;
document.getElementById("gameArea").appendChild(span);
var span = document.createElement('span');
span.id = "score-" + name;
span.innerHTML = "0";
document.getElementById("gameArea").appendChild(span);
var inputSText = document.createElement('input');
inputSText.type = "button";
inputSText.value = "Add Points";
inputSText.onclick = function(){AddPoints(name);};
document.getElementById("gameArea").appendChild(inputSText);
};
function AddPoints(player){
document.load(document.getElementById("#score-"+ player).innerHTML = "Please work");
};
<html>
<head>
<title>Game Score Keeper</title>
</head>
<body>
<h2>Game Score Keeper</h2>
<input type="text" id="name" />
<input type="button" value="Add Player" onclick="AddPlayer()" />
<div id="gameArea">
</div>
<script src="index.js"></script>
</body>
</html>
下面是該項目 http://jsfiddle.net/jwmm6rk7/
兄弟的感謝!這真是一個小白菜的錯誤。有趣的是我沒有注意到它。再次感謝。 – Julind
貌似你是jQuery用戶 – vinayakj
不是。我使用的document.load()是爲了測試是否可能使用它,Id會被拾取,並且我不知道這與jQuery有關。仍然得到JavaScript的真正掛起。 – Julind