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