XForms/在表格中插入和刪除
外觀
< XForms
您希望在表格中插入和刪除記錄。在此示例中,記錄將附加到表格末尾,但任何選定的行都可以被刪除。此示例進行“就地”表格編輯。除了實際表格外,沒有其他單獨的表單來啟用檢視新記錄。

<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ev="http://www.w3.org/2001/xml-events"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xf="http://www.w3.org/2002/xforms">
<head>
<style type="text/css">
@namespace xf url("http://www.w3.org/2002/xforms");
* { font-family: Ariel, Helvetica, sans-serif }
.table-header {
display: table-row;
}
.column-header {
display: table-cell;
text-align: center;
width: 185px;
color: white;
background-color: gray;
font-weight: bold;
}
</style>
<title>Demonstration of inserting and deleting records from a table</title>
<xf:model id="phone-list">
<xf:instance id="my-phone-list" src="phone-list.xml" xmlns="" />
<xf:submission id="update-from-local-file" method="get" action="phone-list.xml"
replace="instance" instance="my-phone-list"/>
<xf:submission id="view-xml-instance" method="get" action="phone-list.xml" />
<xf:submission id="save-to-local-file" method="put" action="phone-list.xml" />
</xf:model>
</head>
<body>
<!-- table header -->
<div class="table-header">
<div class="column-header">Name</div>
<div class="column-header">Phone</div>
</div>
<!-- For each Person in the PersonList display the name and phone-->
<xf:repeat ref="/PhoneList/Person" id="repeatPerson">
<xf:input id="name-input" ref="Name"/>
<xf:input ref="Phone"/>
<br/>
</xf:repeat>
<xf:trigger>
<xf:label>Add Person</xf:label>
<xf:action ev:event="DOMActivate">
<xf:insert ref="/PhoneList/Person[last()]" position="after" at="last()"/>
<xf:setvalue ref="/PhoneList/Person[last()]/Name" value="''"/>
<xf:setvalue ref="/PhoneList/Person[last()]/Phone" value="''"/>
<!-- put the cursor in the name field -->
<xf:setfocus control="name-input"/>
</xf:action>
</xf:trigger>
<xf:trigger>
<xf:label>Delete Person</xf:label>
<xf:delete nodeset="/PhoneList/Person[index('repeatPerson')]"
at="index('repeatPerson')" ev:event="DOMActivate" />
</xf:trigger>
<br/>
<xf:submit submission="update-from-local-file">
<xf:label>Reload</xf:label>
</xf:submit>
<xf:submit submission="save-to-local-file">
<xf:label>Save</xf:label>
</xf:submit>
<xf:submit submission="view-xml-instance">
<xf:label>View XML Instance</xf:label>
</xf:submit>
</body>
</html>
此示例使用 last() 和 index() XPath 函式來找出應操作表格的哪一行。
您還可以建立一個版本,該版本在每行中都有一個刪除和新增按鈕。在此設計中,index() 函式用於刪除當前選定的行,並在當前選定的行之後插入。
在某些應用程式中,行的順序很重要。您還可以向每行新增按鈕以將選定的行上移或下移。
請注意,在新增行之後,您應該將插入游標移動到第一個欄位。這是透過使用 setfocus 元素來完成的。