【发布时间】:2011-11-30 04:34:16
【问题描述】:
我的代码似乎不是最优的。我想将 Reorder 函数的内容减少为单个 jquery 函数。它可以做得更简单,或者这是一个好方法?
HTML:
<div id="sortable">
<div class="i">
@<input type="text" name="first" value="" />
</div>
<div class="i">
@<input type="text" name="last" value="" />
</div>
</div>
<a href="#" id="add_input">Add</a>
JS:
$(function(){
$("#sortable").sortable({
containment: "document",
axis: "y",
update: Reorder,
});
function Reorder()
{
$("#sortable input").attr("name", function(i){
//if(i==0){return "first";}
//else{return "waypoint" + (i + 1); }
return "middle" + i;
});
$("#sortable input:first").attr("name", "first");
$("#sortable input:last").attr("name", "last");
}
$("#add_input").click(function () {
var inputIndex = $("#sortable > .i").length;
$("#sortable input:last").attr("name", function(){
return "middle" + (inputIndex - 1);
});
if(inputIndex>1){
var html = '<div class="i">';
html += '@<input type="text" name="last" value="" /> ';
}
$("#sortable").append(html);
return false;
});
});
演示:jsfiddle
【问题讨论】:
-
我认为你需要重新编辑你问题的顶部 - 它很难阅读......只是出于兴趣为什么你必须使用 name 属性并将 first / last 作为values - 为什么 jQuery 选择器 :first / :last 不适合你?哦,在你的标题上使用拼写检查器......
-
可以,但也许可以做得更好,或者有更好的方法。我需要稍后将中间元素作为位置数组。
-
感谢编辑,现在这篇文章完全表达了我的意思。
-
在javascript中使用lowerCamelCase命名也是一种编码约定。所以
function Reorder()将被命名为function reorder()。
标签: javascript jquery html optimization