2013-02-28 40 views
1

在我的firefox插件中我有一個<listbox>。當我左鍵單擊框中的某個項目時,我希望能夠使用JavaScript功能。該函數應該檢索項目的文本值。現在如何從listbox獲取值listitem

,我的功能確實,當我點擊一個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

我從這裏有gotten the original codegot the EventListener working here

如何獲取listcells的值?我已經嘗試了一切!

回答

0

您不能只是一個listcell檢測click。最接近你可以在listitem上檢測到click。之後,您必須使用代碼深入瞭解。

因此,在您的目標上使用.childNode。由於您的listitem中只有兩個listcell,如果您嘗試捕獲第二個單元格,請使用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);  
}, 
1

您使用此代碼:

while (target && target.localName != "listitem"){ 
    target = target.parentNode; 
} 

它將從實際點擊目標尋找一個<listitem>標籤上去。然而,文本不存儲在<listitem>標籤,它在<listcell> - 所以你只是要尋找一個在層次結構:

while (target && target.localName != "listcell"){ 
    target = target.parentNode; 
} 
alert(target.getAttribute("value")); 
+0

謝謝,弗拉基米爾。這對我有意義。我仍然在這裏學習。但是,現在沒有任何警報。然而,函數IS正在觸發,如果我註釋掉「if(!target)」部分,錯誤控制檯會告訴我它是'null'。但它看起來總是「空」,因爲之後沒有任何火災發生。 – bgmCoder 2013-03-04 00:35:00

+0

你對我有另一個線索嗎? – bgmCoder 2013-03-05 15:16:12

+0

啊!問題是目標是'listitem'而不是'listcell'。 – bgmCoder 2013-03-07 01:52:22