2014-09-03 73 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

相關問題