如何在函数中使用this.id [英] How to use this.id in function
问题描述
没有为this.id分配变量,没有人知道我将this.id传递给findIndex函数的语法吗?
Instead of assigning variable for this.id, does anyone know the syntax of how would I pass this.id into findIndex function?
listing.slideUp(500, function() {
var listing_id = this.id;
// I'd like it to say car[0].id == this.id ?
var index = cars.findIndex(function(car) { return car[0].id === listing_id });
if (index > -1) {
cars.splice(index, 1);
}
});
推荐答案
如果必须使用不支持箭头功能(=>
)的浏览器,则可以选择将this
绑定到该方法.参考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
If you have to use a browser that does not support arrow functions (=>
) then an alternative is to bind the this
to the method. Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
var object = {
id: 'c'
};
console.log(
$('div').filter(
function(index, element){
return element.id == this.id;
}.bind(object)
).get()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
否则,您只能使用一个箭头函数,该函数不会更改this
的上下文.参考 https://developer.mozilla.org/zh- US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Otherwise you can just us an arrow function, which does not change the context of the this
. Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
var array = ['a', 'c', 'e'];
$('div').on('click', function(){
array.forEach(id => {
if (id == this.id) {
console.log(this);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b">b</div>
<div id="c">c</div>
<div id="d">d</div>
这篇关于如何在函数中使用this.id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!