2013-02-17 61 views
2

如果我將this.style.background="#000";內嵌在div中,例如onclick="this.style.background="#000";,它就可以工作。但是,如果我把它放在一個函數中,並從相同的onclick事件中調用該函數,那麼它不起作用。但是,如果我讓該功能做其他事情(如調出一個警告框),它確實有效。這是怎麼回事?如何通過在JavaScript中調用函數來改變onclick的div的顏色?

下面的代碼:

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 
<style> 
.tile { 
    width: 48px; 
    height: 48px; 
    margin: 0px; 
    padding: 0px; 
    float: left; 
    background-color:red; 
    border: 1px solid black; 
} 
</style> 
</head> 

<body> 
<div class="tile" onclick="myFunction()"></div> 

<script> 
function myFunction() { 
    this.style.background="#000000"; 
} 
</script> 

</body> 

</html> 
+1

快速修復:'myFunction的(這個)'...'myFunction的(X){x.style 。'... – 2013-02-17 18:36:20

+0

高級修復是使用[addEventListener](https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener)。 – Teemu 2013-02-17 18:38:52

+0

太棒了,謝謝! – FlyingLizard 2013-02-17 18:40:55

回答

2
<div class="tile" onclick="myFunction(this)"></div> 

<script> 
function myFunction(x) { 
    x.style.background="#000000"; 
} 
</script> 
2

如果你想去做這種方式,你需要通過DIV元素的參考,當你調用你的函數。在執行你的onclick處理程序時,「this」將引用當前元素。把它作爲一個參數傳遞!

以下是更正代碼:

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 
<style> 
.tile { 
width: 48px; 
height: 48px; 
margin: 0px; 
padding: 0px; 
float: left; 
background-color:red; 
border: 1px solid black; 
} 
</style> 
</head> 

<body> 
<div class="tile" onclick="myFunction(this)"></div> 

<script> 
function myFunction(divObj) { 
    divObj.style.background="#000000"; 
} 
</script> 

</body> 

</html> 
+0

還有一點需要注意:我看到你正在加載jquery。如果你這樣做,你爲什麼不使用它?至少爲了改變顏色...在你的函數中你應該使用(檢查jquery引用,但可能這是OK)$(divObj).css({backgroundColor:'#000000'}) – 2013-02-17 18:47:56

+0

你怎麼能夠修復代碼格式? :-)沒有爲我工作...雖然我正確使用了4spaces(理論上):-)謝謝,無論如何! – 2013-02-17 19:17:50

4

我注意到你的jQuery包括。您應該強烈考慮separating your markup and JavaScript。如果你走這條路線,這裏的將是什麼樣子:

<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 
<style> 
.tile { 
    width: 48px; 
    height: 48px; 
    margin: 0px; 
    padding: 0px; 
    float: left; 
    background-color:red; 
    border: 1px solid black; 
} 
</style> 
</head> 

<body> 
<div class="tile"></div> 

<script> 
$(function() { 
    $(".tile").click(function() { 
     $(this).css('background-color', '#000000'); 
    }); 
}); 
</script> 

</body> 

</html> 

例子:http://jsfiddle.net/6zAN7/9/