我有一個mouseenter功能,將選定的div變成紅色和1不透明度。我有一個類「完整」,只是這樣做,但是當我在mouseenter中添加該類時,div不會更改顏色。相反,如果我添加紅色並使用this.style.color和this.style.opacity更改mouseenter內部的不透明度,那麼它似乎工作。我的問題是爲什麼?addClass()在mouseenter()中不起作用?
的jQuery(不工作):
$('.content').mouseenter(function() {
$(".content").each(function (i) {
if (this.style.color != "#F7F7F7") {
this.style.color = "#F7F7F7";
this.style.opacity = "0.5";
}
});
this.addClass('full');
});
的jQuery(WORKING):
$('.content').mouseenter(function() {
$(".content").each(function (i) {
if (this.style.color != "#F7F7F7") {
this.style.color = "#F7F7F7";
this.style.opacity = "0.5";
}
});
this.style.color = "red";
this.style.opacity = "1";
});
CSS:
.full
{
color: red;
opacity: 1;
}
是的,你說得對。你能解釋'this'和'$(this)'之間的區別嗎? – user2441391
'this'是指DOM元素,'$(this)'是封裝在jquery對象中的DOM元素,並向其中添加了jquery方法。 'addClass()'是一個jquery的方法,這就是爲什麼你需要使用jquery對象。 –
這個指的是(在這個例子中)一個DOM節點。 '$(this)'返回一個基於'this'引用的節點的JQuery對象。 jquery對象具有$ function可以訪問的所有方法。一個正常的dom節點不會。 –