onmouseover 和使用“this”的内联函数目的
我有以下代码:
<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;"
onmouseover="(function(){$(this).css('background','green');})();"></div>
该函数运行得很好,但似乎无法找到“this”。 我怎样才能让它知道自我引用?
(是的,我的代码中引用了jquery)
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?
(Yes, jquery is referenced in my code)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不知道你是否想在那里使用匿名函数。我认为
会起作用。
I don't know if you want to be using an anonymous function there. I think
will work.
如果您确实需要将其包装在匿名函数中,则可以这样做。
If you really need to wrap it up in an anonymous function, you can do this.
这将会变得混乱,因为你正在执行该函数。让我们稍微分解一下。
如果这不是内联的,它会看起来像这样:
注意到末尾的 () 了吗?这意味着您正在将函数分配给 onmouseover 之前执行代码。
试试这个:
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:
Notice the () at the end? This means you're executing the code before the function gets assigned to onmouseover.
Try this instead:
<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;"
onmouseover="$(this).css('background','green');"></div>
看来你正在使用 jQuery,为什么不完全这样做呢
Seems you're using jQuery, why not do it all the way
@matt,您可以对 css 执行相同的操作,只需在类上使用
:hover
即可。和
@matt you can do the same with css, just by using the
:hover
on the class.and