消除重复代码 re: lambda 循环参数传递
问题
数组定义了以下元素:
var equipment = new Array( "bakeware", "cookware", "kitchenware", "utensils" );
存在将这些设备类型与可编辑字段关联起来的函数:
function register_equipment( equipment ) {
$('#recipe-equipment-' + equipment).append(
'<span class="edit-recipe-equipment"></span><br />' );
$('.edit-recipe-equipment').editable( 'php/save.php', {
onblur : 'submit',
style : 'display: inline',
maxlength: 15,
size : 10
});
return true;
}
这允许用户单击该字段并编辑其值。当用户完成编辑时,输入字段消失。
以下代码重复四次(每个设备项目一次):
$('#equipment-new-bakeware').click( function() {
return register_equipment( 'bakeware' );
});
这可行,但并不理想。
问题
如何编写代码才能不重复?
以下不起作用,但显示了删除重复的意图:
for( var i = 0; i < equipment.length; i++ ) {
$('#equipment-new-' + equipment[i]).click( function() {
return register_equipment( equipment[i] );
});
}
谢谢!
Problem
An array defines these elements:
var equipment = new Array( "bakeware", "cookware", "kitchenware", "utensils" );
A function exists that associates these equipment types with editable fields:
function register_equipment( equipment ) {
$('#recipe-equipment-' + equipment).append(
'<span class="edit-recipe-equipment"></span><br />' );
$('.edit-recipe-equipment').editable( 'php/save.php', {
onblur : 'submit',
style : 'display: inline',
maxlength: 15,
size : 10
});
return true;
}
This allows users to click on the field and edit its value. The input field disappears when the user finishes editing.
The following code is duplicated four times (once per equipment item):
$('#equipment-new-bakeware').click( function() {
return register_equipment( 'bakeware' );
});
This works, but it is not ideal.
Question
How would you write the code such that there is no duplication?
The following does not work, but shows the intent to remove the duplication:
for( var i = 0; i < equipment.length; i++ ) {
$('#equipment-new-' + equipment[i]).click( function() {
return register_equipment( equipment[i] );
});
}
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
快速答案是创建另一个范围来捕获正确的值。有点啰嗦,但这就是想法。
Quick answer is to create another scope to capture the correct value. Bit long winded, but this is the idea.
从单击对象的 id 中检索设备类型并使用:
Retrieve the equipment type from the id of the clicked object and use that:
尝试一下;)
Give it a try ;)