我正在使用ES6并且有一个问题,showCarOnMap()在$(document).delegate()或$(document).click()
中无法访问实例的一部分实际上我有一个表,通过“$(this).index()”点击$(document).delegate()后找到行号,我想在创建点击的行号后调用showCarOnMap()函数。 但这次'this'没有showCarOnMap();
请参阅评论以便更好地理解。
import {Page} from './framework/page.js';
import {DataTable} from './ui/data-table.js';
import {application} from './app.js';
import {GoogleMap} from './ui/google-map.js';
import {Button} from './ui/button.js';
export class CarsPage extends Page{
constructor(){
super('Cars');
}
createElement(){
super.createElement();
//passing headers and data to genrate the table of car
let headers = 'License Make Model Miles Track'.split(' ');
let t = new DataTable(headers, application.dataService.cars);
t.appendToElement(this.element);
/* Poblem Start here*/
$(document).delegate("tr", "click", function(e) {
let index = $(this).index(); // getting right index
this.showCarOnMap(index); // BUT: not getting showCarOnMap()
//Uncaught TypeError: this.showCarOnMap is not a function
});
}
showCarOnMap(index){
// car on map
let mapArray = [];
mapArray.push(application.dataService.cars[index]);
let centerOfMap = {lat: 40.783661, lng: -73.965883};
let carLabelObject = {titleOfCar:'Car', titleOfDrone:'Drone'};
let carMap = new GoogleMap(centerOfMap, mapArray, carLabelObject);
carMap.appendToElement(this.element);
}
getElementString(){
return '<div style="margin:20px;"><h3>Cars</h3></div>';
}
}
我试了另一种方式 - 但是没有工作
$(document).delegate("tr", "click",(e)=>{
let index = $(this).index(); // wrong: index always -1
this.showCarOnMap(index); // founded in this });
答案 0 :(得分:0)
您可以使用event.target.parentElement
或.closest()
来引用点击的<tr>
元素。
或者,正如@KevinB所建议的,event.currentTarget
$(document).on("click", "tr", event => {
// or `$(event.target).closest("tr").index()`
// or `$(event.currentTarget).index()`
let index = $(event.target.parentElement).index();
this.showCarOnMap(index);
});