简体   繁体   English

在JavaScript中创建可重用函数

[英]Creating a re-usable function in JavaScript

I'm extracting a part of the current button ID and want it to re-use this in several other functions. 我正在提取当前按钮ID的一部分,并希望它在其他几个功能中重复使用。

How could I make the following section common, 我如何才能使以下部分通用,

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

So that it could be used in multiple .on('click',) events. 这样它就可以在多个.on('click',)事件中使用。 Please see the following code and advise, 请查看以下代码并提出建议,

$(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
  });
});
$(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
        })
})

You can declare inp before click function . 您可以在click函数之前声明inp http://fiddle.jshell.net/x3xo25vz/ http://fiddle.jshell.net/x3xo25vz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM