我知道这个问题的变体已经被问了数百次,但在搜索和阅读了几十个类似的问题后,我的问题特别多,我无法弄清楚它发生的原因和方式,所以冒着风险在火焰中被击落......
故障排除我将所有内容都缩减为最基本的,所以我得到了表单的 html
<li class='field' id='field_2'>
如果我把一个 jquery 函数写成
$('.field').on('mouseenter',function(){console.log(this.id)});
它返回 id 正常,但是如果我声明并调用一个函数,例如
function shade(){
console.log(this.id);
};
$('.field').on('mouseenter',function(){shade()});
它返回“未定义”。
还尝试在 shade() 中将 id 作为“var”传递,使用 .attr() 等,以防有所不同但无济于事。
在我放弃并将 id 声明为 mouseenter 中的全局变量之前,任何人都可以指出我做错了什么“傻瓜”将不胜感激。
谢谢!
最佳答案
你应该使用 call()
function shade(){
console.log(this.id);
};
$('.field').on(
'mouseenter',
function(){
shade.call(this)
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class='field' id='field_2'>hover me</li>
关于javascript - this.id 在声明的函数内部时返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347212/