![](/img/trans.png)
[英]How do I get the value of each ListItem in a ListBox using JavaScript
[英]How to get value from listbox listitem
在我的Firefox插件中,我有一個<listbox>
。 當我在框中的項目上單擊鼠標左鍵時,我希望能夠使用javascript函數。 該函數應檢索項目的文本值。
現在,當我單擊listitem
, 確實會調用我的函數,因為已將其放置在事件監聽器的onLoad調用中:
var myListBox = document.getElementById("myListBoxID");
myListBox.addEventListener("click", function(event){
var target = event.target;
while (target && target.localName != "listitem"){
target = target.parentNode;
}
if (!target){
return; // Event target isn't a list item
}
alert(target); //returns blank
alert(target.id); //returns blank
alert(target.getAttribute("value")); //returns blank
alert(target.getAttribute("text")); //returns blank
alert(target.getAttribute("id")); //returns blank
var targetid = document.getElementById(target.id);
alert(targetid); //returns null
}, false);
},
xul是這樣的:
<listbox id="listbox1">
<listcols /><listcol flex="1"/><listcol flex="1"/></listcols>
<listitem><listcell class="column1" label="label1" value="value1"</listcell><listcell label="cell1"></listcell></listitem>
<listitem><listcell class="column2" label="label2" value="value2"</listcell></listitem><listcell label="cell2"></listcell>
</listbox>
但是,我無法顯示項目的文本。 如您在上面看到的,我似乎對target
沒有正確的處理
我從這里獲得了原始代碼 ,並在這里運行了EventListener
。
如何獲得列表單元的值? 我已經嘗試了一切!
您正在使用以下代碼:
while (target && target.localName != "listitem"){
target = target.parentNode;
}
它將從實際的點擊目標中向上尋找<listitem>
標記。 但是文本沒有存儲在<listitem>
標記中,而是存儲在<listcell>
-因此,您只需要在層次結構中查找該文本即可:
while (target && target.localName != "listcell"){
target = target.parentNode;
}
alert(target.getAttribute("value"));
你無法檢測click
上只是一個listcell
。 你可以去最近的是檢測click
一個listitem
。 之后,您必須使用代碼進行深入研究。
因此,在目標上使用.childNode
。 既然你只有兩個listcell
在你的S listitem
,如果你想捕捉第二個單元格,使用childNodes[1]
childNodes [0]將引用第一個單元格。
onLoad: function(){
var mylistbox= document.getElementById("mylistboxID");
mylistbox.addEventListener("click", function(event){
var target = event.target.childNodes[1];
if (!target){
return; // In case there is not target
}
alert(target.getAttribute("label") + target.getAttribute("label"));
}, false);
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.