2017-03-04 151 views
0

我嘗試執行jquery更改div的背景顏色,但所有內部的php代碼,並將鼠標放在這個div時,應該改變背景的顏色,但我認爲寫一些壞東西,不要'T得到這樣的效果終於jquery更改div的背景顏色時鼠標懸停

我的代碼it's簡單it's這樣:

echo '<div id="rating_poll_front" onmouseover="this.css("background-color","red")" onmouseleave="this.css("background-color","yellow");" style="background-color:yellow;"></div> '; 

Thank's爲幫助社區,問候!

+0

'this'給HTMLElement對象沒有'.css()'。改用'$(this)'。 –

+0

,因爲'this'不是一個jQuery對象 –

回答

2

您應該使用$(this)因爲this回報它不具有的功能css()一個HTML元素。
或者,您可以使用this.style.backgroundColor=yellow

請逃跑或者使用單引號一組雙引號

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="rating_poll_front" onmouseover="$(this).css('background-color','red')" onmouseleave="$(this).css('background-color','yellow');" style="background-color:yellow;">dsfdsf</div>

內部在普通的JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="rating_poll_front" onmouseover="this.style.backgroundColor='red';" onmouseleave="this.style.backgroundColor='yellow';" style="background-color:yellow;">dsfdsf</div>

1

嘗試使用$(本),而不是這個

echo '<div id="rating_poll_front" onmouseover="$(this).css(\'background-color\',\'red\')" onmouseleave="$(this).css(\'background-color\',\'yellow\');" style="background-color:yellow;"></div> '; 
1

第一:

當您使用雙引號在HTML中使用單引號」在其屬性

<div id="rating_poll_front" onmouseover="this.css("background-color","red")" onmouseleave="this.css("background-color","yellow");" style="background-color:yellow;"></div> 

應該是:

<div id="rating_poll_front" onmouseover="this.css('background-color','red')" onmouseleave="this.css('background-color','yellow');" style="background-color:yellow;"></div> 

二:

由於PHP代碼也使用單引號內的PHP的單引號之前,所以用一個反斜槓:

例如:

echo '<div id="rating_poll_front" onmouseover="this.css(\'background-color\',\'red\')" onmouseleave="this.css(\'background-color\',\'yellow\');" style="background-color:yellow;"></div>'; 

第三,在javascript中沒有像css()那樣的屬性,請使用this.style。的backgroundColor:

所以,你的代碼最終變爲:

echo '<div id="rating_poll_front" onmouseover="this.style.backgroundColor=\'red\';" onmouseleave="this.style.backgroundColor=\'yellow\';" style="background-color:yellow;">Hello</div>'; 

當談到瀏覽器將運行像片段:

<div id="rating_poll_front" onmouseover="this.style.backgroundColor='red';" onmouseleave="this.style.backgroundColor='yellow';" style="background-color:yellow;">Hello</div>

相關問題