Onmouseover和内联函数使用'this'对象

onmouseover and inline function using the 'this' object

本文关键字:this 对象 函数 Onmouseover      更新时间:2023-09-26

我有以下代码:

<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;" 
onmouseover="(function(){$(this).css('background','green');})();"></div>

函数运行得很好,但似乎无法找到"this"。我怎样才能使它知道自我引用呢?

(是的,jquery在我的代码中被引用)

我不知道你是否想在那里使用匿名函数。我认为

<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;" 
onmouseover="$(this).css('background','green');"></div>

如果您确实需要将其封装在一个匿名函数中,您可以这样做。

onmouseover="(function(that){$(that).css('background','green');})(this);"

这会很混乱,因为你正在执行这个函数。

如果这不是内联的,它看起来像这样:

onmouseover = (function(){
    $(this).css('background','green');
})();

注意到末尾的()了吗?这意味着你在函数被赋值给onmouseover之前执行代码。

试试这个:

<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;" onmouseover="$(this).css('background','green');"></div>

似乎你正在使用jQuery,为什么不做它所有的方式

$('#tag').hover(function() { $(this).css('background', 'green'); });
<div id="tag"> ... </div>

@matt你可以用css做同样的事情,只需要在类上使用:hover

.SomeDiv
{
    border: solid 1px red; 
    width:50px; 
    height: 50px;
    /*remove the below line if you like to keep the hover color*/
    background-color:white;
}
.SomeDiv:hover
{
    background-color:green;
}

<div id="some_div" class="SomeDiv"></div>