jquery更改div的背景颜色时鼠标悬停
问题描述:
我尝试执行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为帮助社区,问候!
答
您应该使用$(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>
答
尝试使用$(本),而不是这个
echo '<div id="rating_poll_front" onmouseover="$(this).css(\'background-color\',\'red\')" onmouseleave="$(this).css(\'background-color\',\'yellow\');" style="background-color:yellow;"></div> ';
答
第一:
当您使用双引号“在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>
'this'给HTMLElement对象没有'.css()'。改用'$(this)'。 –
,因为'this'不是一个jQuery对象 –