在JavaScript中创建可重用的函数

时间:2014-09-03 05:38:37

标签: javascript jquery

我提取当前按钮ID的一部分,并希望它在其他几个功能中重复使用。

我怎样才能使以下部分变得通用,

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

2 个答案:

答案 0 :(得分: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
        })
})

答案 1 :(得分:0)

您可以在点击功能之前声明 inp http://fiddle.jshell.net/x3xo25vz/

相关问题