- 创建.html文件
引入jquery
<input type="text" id="J_input" />
- 创建js文件
var textCount = {
input: null,
getNum: 0,
init: function (config) {
this.input = $(config.id)
this.bindEvent();
return this;
},
bindEvent() {
var that = this;
/* // 方法一 应该是好多人一开始最喜欢用的,最省事的
this.input.on('keyup', function () {
that.render()
}); */
// 方法二 因为bind仍然返回一个函数,所以在这里可以这么用
this.input.on('keyup', this.render.bind(this));
/*
// 方法 三 这个是jquery提供的方法(接受两个参数,第一个是一个函数,第二个要改变成的执行环境)
this.input.on('keyup', $.proxy(function () {
this.render()
}, this)); */
/* // 方法 四 这个是jquery提供的方法 其实同上一个方法, 在这里 this.render没有加括号,标识引用这个函数而不是执行
this.input.on('keyup', $.proxy(this.render, this)); */
/* // 方法五 es6的箭头函数
this.input.on('keyup', () =>{
this.render()
}); */
},
render() {
this.getNumF();
if ($('#J_input_count').length == 0) {
this.input.after('<span id="J_input_count">' + this.getNum + '</span>');
}
$('#J_input_count').html(this.getNum + '个字');
},
getNumF() {
this.getNum = this.input.val().length || 0;
}
}
textCount.init({
id: "#J_input"
}).render()