Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用';这';对象_Javascript_Jquery_Html_Onmouseover - Fatal编程技术网

Javascript 使用';这';对象

Javascript 使用';这';对象,javascript,jquery,html,onmouseover,Javascript,Jquery,Html,Onmouseover,我有以下代码: <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="(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之前执行代码

请尝试以下方法:


@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;
}


您似乎正在使用jQuery,为什么不一直使用它呢

$('#tag').hover(function() { $(this).css('background', 'green'); });

他可能不想删除
mouseout
上的背景。(至少来自他的代码片段)。@Dogbert这很简单,你不需要在.SomveDiv上使用背景色,只需要在hover上使用。如果我使用你的代码来回悬停,绿色就会消失。但op的原始代码将保持绿色。@Dogbert在我对代码进行注释时删除一行,绿色代码将保留为什么使用内联函数?将其分开(将代码与设计分开)更有意义。
$('#tag').hover(function() { $(this).css('background', 'green'); });
<div id="tag"> ... </div>