2015-04-06 76 views
-1

我不能讓我的球換到另一個字符,我做錯了什麼?這是完整的代碼量,並且我附加了一個html文件,它只是調用球變化按鈕。我只能得到被調用的按鈕,我不能讓它將「」更改爲另一個角色。更改球功能

window.onload = initAll; 
var moves = new Array('Up','Down','Right','Left'); 

function initAll() { 
for (var i=0; i<moves.length; i++) { 
    var eid="id_"+moves[i]; 
    console.log('eid='+eid); 
    document.getElementById(eid).onclick = 
    function() {moveBall(this);} 
} 


function moveBall(e) { 
    console.warn('moveBall['+e.id+']'); 
var ball = document.getElementById("id_ball"); 
var tl=GetTopLeft(ball); 
console.log('tl["Top"]='+tl["Top"]+' tl["Left"]='+tl["Left"]); 
switch (e.id) { 
case "id_Up": 
    ball.style.top = tl['Top'] - 15 + 'px'; 
break; 
case "id_Down": 
    ball.style.top = tl['Top'] + 15 + 'px'; 
break; 
case "id_Right": 
    ball.style.left = tl['Left'] + 15 + 'px'; 
break; 
case "id_Left": 
    ball.style.left = tl['Left'] - 15 + 'px'; 
break; 
} 
} 


function GetTopLeft(e) { 
var x, y = 0; 
//set x to e’s offsetLeft 
x = e.offsetLeft; 
//set y to e’s offsetTop 
y = e.offsetTop; 
//set e to its offsetParent 
e = e.offsetParent; 
//use while loop to check if e is null 
//if not then add current e’s offsetLeft to x 
//offsetTop to y and set e to its offsetParent 
while(e != null) { 
    x = parseInt(x) + parseInt(e.offsetLeft); 
    y = parseInt(y) + parseInt(e.offsetTop); 
    console.log(x); 
    e = e.offsetParent; 
} 
//Return Top and Left 
return {Left:x, Top:y}; 
} 

function changeBallChar() { 
    var ball = prompt("Please enter character for ball", "*"); 
    {document.getElementById(id_ball).innerHTML = ball;} 
} 
+0

不要想聲明VAR id_ball =提示符(...)? –

+0

我在上面添加了我的完整代碼,我在我的html文件中調用了id_ball。如果一個人放入* in以外的東西,按鈕的作用就不會改變對象。 – Amy

回答

1

您的Javascript缺少最後的結尾括號。

試試下面的代碼:

function changeBallChar() { 
    var ball = prompt("Please enter character for ball", "*"); 
    if(ball != null) { 
     // id_ball is not defined inside this the code you posted 
    } 
} 

看看這裏的JS彈出更多的文檔:http://www.w3schools.com/js/js_popup.asp