javascript 使用“this”对象的 onmouseover 和内联函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6716059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onmouseover and inline function using the 'this' object
提问by Matt
I have the following bit of code:
我有以下代码:
<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;"
onmouseover="(function(){$(this).css('background','green');})();"></div>
The function gets run just fine but it doesn't seem to be able to find the 'this'. How can I make it so that it will know to self-reference?
该函数运行得很好,但似乎无法找到“this”。我怎样才能让它知道自我参考?
(Yes, jquery is referenced in my code)
(是的,我的代码中引用了 jquery)
采纳答案by Paul
I don't know if you want to be using an anonymous function there. I think
我不知道你是否想在那里使用匿名函数。我认为
<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;"
onmouseover="$(this).css('background','green');"></div>
will work.
将工作。
回答by Dogbert
If you really need to wrap it up in an anonymous function, you can do this.
如果你真的需要将它封装在一个匿名函数中,你可以这样做。
onmouseover="(function(that){$(that).css('background','green');})(this);"
回答by beatgammit
This is going to be messed up because you're executing the function. Let's break this up a little.
这将被搞砸,因为您正在执行该功能。让我们稍微分解一下。
If this was not inline, it would look like this:
如果这不是内联的,它看起来像这样:
onmouseover = (function(){
$(this).css('background','green');
})();
Notice the () at the end? This means you're executing the code before the function gets assigned to onmouseover.
注意到最后的 () 了吗?这意味着您正在将函数分配给 onmouseover 之前执行代码。
Try this instead:
试试这个:
<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;"
onmouseover="$(this).css('background','green');"></div>
<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;"
onmouseover="$(this).css('background','green');"></div>
回答by Aristos
@matt you can do the same with css, just by using the :hover
on the class.
@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;
}
and
和
<div id="some_div" class="SomeDiv"></div>
回答by casraf
Seems you're using jQuery, why not do it all the way
好像你在用 jQuery,为什么不一直用
$('#tag').hover(function() { $(this).css('background', 'green'); });
<div id="tag"> ... </div>