[英]Creating a re-usable function in JavaScript
我正在提取当前按钮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
});
});
$(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
})
})
您可以在click函数之前声明inp 。 http://fiddle.jshell.net/x3xo25vz/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.