在JavaScript中创建可重用函数
我正在提取当前按钮ID的一部分,并希望它在其他几个函数中重复使用 我怎样才能使下面的部分变得通用在JavaScript中创建可重用函数,javascript,jquery,Javascript,Jquery,我正在提取当前按钮ID的一部分,并希望它在其他几个函数中重复使用 我怎样才能使下面的部分变得通用 var idRec = $(this).attr("id"), inp = idRec.substr(4,this.id.length); 这样它就可以在多个点击事件中使用。请参阅以下代码并建议: $(function() { function studentsRecords(e) { //do_somehting } $(document).on('click', '.stud
var idRec = $(this).attr("id"),
inp = idRec.substr(4,this.id.length);
这样它就可以在多个点击事件中使用。请参阅以下代码并建议:
$(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
});
});
您可以在单击函数之前声明inp 只需删除关键字var并添加var idRec,inp;在$document.on'click'之前,单击两次就好像你在单击是错误的…@levi-还有$that.attrid可以简化为that.id:,别忘了将this.id.length更改为that.id.length。
$(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
})
})