有没有人知道如何将this.id传递给findIndex函数的语法,而不是为this.id分配变量?
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);
}
});
答案 0 :(得分:0)
如果您必须使用不支持箭头功能的浏览器(=>
),那么另一种方法是将this
绑定到该方法。参考。 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>
&#13;
否则你可以使用箭头函数,它不会改变this
的上下文。参考。 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);
}
});
});
&#13;
<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>
&#13;