Javascript 将额外参数传递给事件处理程序
在下面的代码中,我使用了Javascript 将额外参数传递给事件处理程序,javascript,jquery,Javascript,Jquery,在下面的代码中,我使用了util.doSomething()方法,该方法将json对象作为参数。当util完成某项操作时,它通过传递响应作为参数来调用onDone事件处理程序 我想在下面的代码中知道是否可以将id传递给update事件处理程序 $(function(){ $('#btn').click(function(){ var id = $(this).attr('id'); util.doSomething({ property1: "Some
util.doSomething()
方法,该方法将json对象作为参数。当util完成某项操作时,它通过传递响应作为参数来调用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
}
})
})
您可以将其设置为使用所需参数调用update
的函数,而不是将onDone
设置为update
util.doSomething({
property1: "SomeValue1",
property2: "SomeValue2",
onDone: function(response) {
return update(response, id);
}
})
您可以将其设置为使用所需参数调用update
的函数,而不是将onDone
设置为update
util.doSomething({
property1: "SomeValue1",
property2: "SomeValue2",
onDone: function(response) {
return update(response, id);
}
})
可以在函数中使用.bind方法和arguments对象来访问要传入的额外参数
$(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
}
})
可以在函数中使用.bind方法和arguments对象来访问要传入的额外参数
$(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
}
})
如果不知道您的所做的事情
正在做什么,就不可能真正知道可以做什么。您可以将id附加到调用onDone的对象上。通常在运行事件时,将this
设置为调用对象或元素。那么使用内联函数有什么问题?否则,您需要修改doSomething
以获取额外的id
参数并将其传递给onDone
,而不知道您的doSomething
正在做什么,实际上不可能知道可以做什么。您可以将id附加到调用onDone的对象上。通常在运行事件时,将this
设置为调用对象或元素。那么使用内联函数有什么问题?否则,您需要修改doSomething
以获取额外的id
param并将其传递给onDone