我非常感谢有关解决此问题的最有效方法的建议。
我正在构建一个简单的 javascript 应用程序,它显示记录列表并允许用户通过单击记录行中的“编辑”链接来编辑记录。用户还可以单击“添加”链接弹出一个对话框,允许他们添加新记录。
这是一个工作原型:http: //jsfiddle.net/FfRcG/
您会注意到,如果您单击“编辑”,则会弹出一个对话框,其中包含一些固定值。而且,如果您单击“添加”,则会弹出一个包含空值的对话框。
我需要有关如何解决两个问题的帮助
我相信我们需要将索引传递给我们的编辑对话框并引用 JSON 中的值,但我不确定当用户单击编辑时如何传递索引。
令我困扰的是 Edit 和 Add div 的内容是如此相似(Edit 只是预先填充了值)。我觉得有一种更有效的方法可以做到这一点,但不知所措。
这是我的代码供参考
$(document).ready( function(){
// Our JSON (This would actually be coming from an AJAX database call)
people = {
"COLUMNS":["DATEMODIFIED", "NAME","AGE"],
"DATA":[
["9/6/2012", "Person 1","32"],
["9/5/2012","Person 2","23"]
]
}
// Here we loop over our JSON and build our HTML (Will refactor to use templating eventually)
members = people.DATA;
var newcontent = '<table width=50%><tr><td>date</td><td>name</td><td>age</td><td></td></tr>';
for(var i=0;i<members.length;i++)
{
newcontent+= '<tr id="member'+i+'"><td>' + members[i][0] + '</td>';
newcontent+= '<td>' + members[i][1] + '</td>';
newcontent+= '<td>' + members[i][2] + '</td>';
newcontent+= '<td><a href="#" class="edit" id=edit'+i+'>Edit</a></td><td>';
}
newcontent += "</table>";
$("#result").html(newcontent);
// Bind a dialog to the edit link
$(".edit").click( function(){
// Trigger our dialog to open
$("#edit").dialog("open");
// Not sure the most efficient way to change our dialog field values
$("#name").val() // ???
alert($());
return false;
});
// Bind a dialog to the add link
$(".edit").click( function(){
// Trigger our dialog to open
$("#add").dialog("open");
return false;
});
// Bind a dialog to our edit DIV
$("#edit").dialog();
// Bind a dialog to our add DIV
$("#add").dialog();
});
这是HTML
<h1>People</h1>
<a href="#" class="add">Add a new person</a>
<!-- Where results show up -->
<div id="result"></div>
<!--
Here's our edit DIV - I am not clear as to the best way to pass the index in our JSON so that we can reference positions in our array to pre populate the input values.
-->
<div id="edit">
<form>
<p>Name:<br/><input type="text" id="name" value="foo"></p>
<p>Age:<br/><input type="text" id="age" value="33"></p>
<input type="submit" value="Save" id="submitEdit">
</form>
</div>
<!--
Here's our add DIV - This layout is so similiar to our edit dialog. What is the
most efficient way to handle a situation like this?
-->
<div id="add">
<form>
<p>Name:<br/><input type="text" id="name"></p>
<p>Age:<br/><input type="text" id="age"></p>
<input type="submit" value="Save" id="submitEdit">
</form>
</div>