XUL中的列表操作

List manipulation in XUL

本文关键字:操作 列表 XUL      更新时间:2023-09-26

我想找出一种简单的方法来编辑/添加/删除XUL列表上的项目。我最初的想法是用一个单独的文件来处理所有这些,但我不确定如何用另一个文件影响主XUL。到目前为止,我的列表看起来像:

<?xml version = "1.0"?>
<!DOCTYPE window>
<window title = "Hello"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" >
<script>
</script>
<listbox id = "mainList" flex = "1">
    <listhead>
    <listheader label = "Album Name"/>
    <listheader label = "Artist"/>
    <listheader label = "Year"/>
    <listheader label = "Sales"/>
    <listheader label = "Rating"/>
    <listheader label = "Genre"/>
    <listheader label = "Edit" />
    <listheader label = "Delete"/>
</listhead>
<listitem id = "1">
    <listcell label = "OK Computer"/>
    <listcell label = "Radiohead"/>
    <listcell label = "1997"/>
    <listcell label = "Platinum"/>
    <listcell label = "5/5"/>
    <listcell label = "Alternative Rock"/>  
    <button label = "Edit" oncommand= "editItem()"/>
    <button label = "Delete" oncommand = "deleteItem()"/>   
</listitem>
<listitem>
    <listcell label = "The Moon and Antarctica"/>
    <listcell label = "Modest Mouse"/>
    <listcell label = "2000"/>
    <listcell label = "Gold"/>
    <listcell label = "4.5/5"/>
    <listcell label = "Alternative Rock"/>
    <button label = "Edit"/>
    <button label = "Delete"/>
</listitem>
<listitem>
    <listcell label = "Pinkerton"/>
    <listcell label = "Weezer"/>
    <listcell label = "1996"/>
    <listcell label = "Gold"/>
    <listcell label = "5/5"/>
    <listcell label = "Alternative Rock"/>
    <button label = "Edit"/>
    <button label = "Delete"/>
</listitem>
<listitem>
    <listcell label = "Helplessness Blues"/>
    <listcell label = "Fleet Foxes"/>
    <listcell label = "2011"/>
    <listcell label = "Gold"/>
    <listcell label = "4/5"/>
    <listcell label = "Folk Pop"/>
    <button label = "Edit"/>
    <button label = "Delete"/>
</listitem>
</listbox>
</window>

相当简单,但我对我需要什么javascript来使按钮实际工作感到困惑。理想情况下,我希望有一个Add按钮,将打开一个新窗口,每个列的空白字段,然后将新行添加到列表中。实现这一目标的最佳方式是什么?

使用常规的DOM操作函数。当动态添加项目时,如果你有一个"模板",你可以克隆和修改,例如:

<listitem id="template" hidden="true">
    <listcell class="album"/>
    <listcell class="title"/>
    <listcell class="year"/>
    <listcell class="group"/>
    <listcell class="rating"/>
    <listcell class="category"/>  
    <button label="Edit" oncommand="editItem()"/>
    <button label="Delete" oncommand="deleteItem()"/>   
</listitem>

你可以像这样添加一个新条目:

var item = document.getElementById("template").cloneNode(true);
item.removeAttribute("id");
item.removeAttribute("hidden");
item.getElementsByClassName("album")[0].setAttribute("label", albumName);
item.getElementsByClassName("title")[0].setAttribute("label", songName);
...
document.getElementById("mainList").appendChild(item);

修改现有条目的文本也是类似的。你必须从某个地方获得新的文本-添加文本字段进行编辑是你的责任,但是,列表没有内置的编辑功能。

删除项显然更简单:

var item = document.getElementById("item1");
item.parentNode.removeChild(item);