2014-09-03 78 views
-1

我正在提取当前按钮ID的一部分,并希望它在其他几个函数中重用。在JavaScript中创建可重用函数

我如何才能让下面的部分常见,

var idRec = $(this).attr("id"), 
inp = idRec.substr(4,this.id.length); 

,以便它可以在多个.on('click',)活动中使用。请看下面的代码,并建议,

$(function() { 
    function studentsRecords(e) { 
     //do_somehting 
} 

$(document).on('click', '.studentID', function(e) { 
    var idRec = $(this).attr("id"), 
    inp = idRec.substr(2, this.id.length); 
    //do_something_using_inp 
    }).on('click', '.admissionID', function(e) { 
    //do_something_else_using_inp 
    }); 
}); 
+0

只是删除关键字'var'并添加'变种idRec,INP;''之前$(文件)。在('click'' – Regent 2014-09-03 05:43:19

+0

两次上点击就像你有错... – 2014-09-03 05:43:24

回答

2
$(function() { 
    function studentsRecords(e) { 
     //do_somehting 
    } 

    function get_id(that){ 
     var idRec = that.id; 
     var inp = idRec.substr(2,that.id.length); 
     return inp 
    } 


    $(document) 
     .on('click', '.studentID', function(e) { 

      var inp = get_id(this); 
      //do_something_using_inp 
     }) 
     .on('click', '.admissionID', function(e) { 
      var inp = get_id(this); 
      //do_something_else_using_inp 
     }) 
}) 
+0

@Derek朕会功夫fixed – levi 2014-09-03 05:47:52

+1

@levi - 还可以将'$(that).attr(“id”)'简化为'that.id' :),不要忘记将'this.id.length'更改为'that.id.length'。 – 2014-09-03 05:48:58

+0

@Derek朕会功夫谢谢你。 – levi 2014-09-03 05:50:29

相关问题