Onmouseover和内联函数使用'this'对象
onmouseover and inline function using the 'this' object
我有以下代码:
<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>
相关文章:
- 警告 - 全局 THIS 对象的危险使用
- 为什么当我尝试将函数绑定到自身时,“this”对象仍然引用窗口
- 在茉莉花中传递“this”对象流星方法
- Jquery $.ajax 获取响应与将“this”对象嵌套传递到“success”回调函数冲突
- 如何将事件的“this”对象更改为其他函数
- 如何通过锚点链接将“this”对象传递给函数,并将其转换为jQuery对象
- 如何使用绑定事件在按钮单击时获取当前/this对象
- 存储'this'对象中的onclick属性
- AngularJs——设置'this'对象在控制器中的$http调用
- 为什么不是在 JavaScript 中匿名函数之外访问“this”对象的关键字
- 为什么调用array.prototype. foreach .call()时将数组设置为THIS对象不能工作?
- JavaScript 方法链接和 this 对象
- 使用'this'对象构造函数中的变量
- 由事件监听器绑定的函数如何继承' this '对象?
- 如何访问“this”;对象
- while循环和"this"对象
- Javascript send "this"对象作为参数
- 使用“this"对象方法内部的关键字
- Onmouseover和内联函数使用'this'对象
- 使用"for "循环全局"this"对象