将额外参数传递给事件处理程序

时间:2017-05-04 18:49:30

标签: javascript jquery

在下面的代码中,我有util.doSomething()方法,它将json对象作为参数。当util执行某些操作时,它会通过传递onDone作为参数来调用response事件处理程序。

我想在下面的代码中知道是否可以将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
         }
      })
  })

2 个答案:

答案 0 :(得分:1)

您可以将其设置为使用您想要的参数调用onDone的函数,而不是将update设置为update

util.doSomething({
    property1: "SomeValue1",
    property2: "SomeValue2",
    onDone: function(response) {
      return update(response, id);
    }
})

答案 1 :(得分:1)

您可以使用.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
   }
})