将额外参数传递给事件处理程序
问题描述:
在下面的代码中,我有util.doSomething()
方法,它将json对象作为参数。当util完成时,它通过传递response
作为参数来调用onDone
事件处理程序。将额外参数传递给事件处理程序
我想知道下面的代码是否有可能通过id
到update
事件处理程序?
$(function(){
$('#btn').click(function(){
var id = $(this).attr('id');
util.doSomething({
property1: "SomeValue1",
property2: "SomeValue2",
onDone: update //ho do i pass id to update event handler?
})
})
function update(response,id)
{
//update
}
})
我知道我可以使用内联事件处理程序获取id。像
$("#btn").click(function(){
var id = $(this).attr('id');
util.doSomething({
property1: "SomeValue1",
property2: "SomeValue2",
onDone: function(response){
// now i can use id here
}
})
})
答
可以使用.bind方法和参数对象在函数内部访问你想在
$(function(){
$('#btn').click(function(){
var id = $(this).attr('id');
util.doSomething({
property1: "SomeValue1",
property2: "SomeValue2",
onDone: update.bind(this, id)
})
})
function update()
{
console.log(arguments); // inside arguments you should see all your parameters
// arguments[0] your id
// arguments[1] your response
}
})
答
而不是设置onDone
到update
的,你可以将其设置为调用update
你想要的参数的函数。
util.doSomething({
property1: "SomeValue1",
property2: "SomeValue2",
onDone: function(response) {
return update(response, id);
}
})
到额外的参数传递不知道你的'doSomething'是做什么的,它不是真的有可能知道可以做些什么。你可以将id附加到调用'onDone'的对象上。通常情况下,事件是通过将this设置为调用对象或元素来运行的。 –
所以最新错误使用内联函数?否则你需要修改'doSomething'来增加'id'参数并将其传递给'onDone' – Jag