在JavaScript中创建一个可重复使用的函数

Creating a re-usable function in JavaScript

本文关键字:函数 一个 JavaScript 创建      更新时间:2023-09-26

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

,我如何使以下部分变得通用

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

从而可以在多个CCD_ 1事件中使用。请参阅以下代码并提出建议,

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

您可以在单击函数之前声明inp。http://fiddle.jshell.net/x3xo25vz/