我正在尝试巧妙地打包一些将编辑控件添加到表格单元格的功能。下面是我想要实现的一个例子。
我想知道的是这是否是正确的方法。当我清空单元格时,我最终不得不重新绑定事件处理程序。我认为 jquery 删除了它们,但我不确定。我希望它们会保留下来,因为我已将 dom 元素保存在 ScoreManager 对象中。
<div id="main">
<table id="points-table">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</thead>
<tr>
<td>Joe</td>
<td>Bloggs</td>
<td class="points">
<span>100</span>
<button>edit</button>
</td>
</tr>
<tr>
<td>Jiminy</td>
<td>Cricket</td>
<td class="points">
<span>77</span>
<button>edit</button>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
window.onload = init;
var ScoreManagers = [];
function init() {
$('#points-table .points').each(function(){
ScoreManagers.push( new ScoreManager(this) );
});
}
var ScoreManager = function(cell) {
this.cell = $(cell);
this.edit = $('button', this.cell);
this.points = $('span', this.cell);
this.scoreInput = $('<input>');
this.submit = $('<button>Submit</button>');
this.cancel = $('<button>Cancel</button>');
this.init();
};
ScoreManager.prototype.init = function() {
this.edit.bind('click', $.proxy(this.showEditControls, this));
};
ScoreManager.prototype.showEditControls = function(e) {
this.cell.empty();
this.cell.append(this.scoreInput, this.submit, this.cancel);
this.submit.bind('click', $.proxy(this.savePoints, this));
this.cancel.bind('click', $.proxy(this.cancelEdit, this));
};
ScoreManager.prototype.cancelEdit = function() {
this.cell.empty();
this.cell.append(this.points, this.edit);
this.edit.bind('click', $.proxy(this.showEditControls, this));
}
ScoreManager.prototype.savePoints = function() {
this.cell.empty();
this.points.text(this.scoreInput.val());
this.cell.append(this.points, this.edit);
this.edit.bind('click', $.proxy(this.showEditControls, this));
}
</script>