在XUL中动态添加和选择菜单项

时间:2011-09-28 19:31:18

标签: javascript xul menuitem

我正在使用包含电话代码列表的Javascript对象来生成XUL中的下拉菜单。我的对象有这样的形式:

var CountryCodes = {
  "Afghanistan":"+93",
  "Albania":"+355",
  "Algeria":"+213"
}

填充menupopup的代码如下所示:

var docfrag = document.createDocumentFragment();

for( var country in CountryCodes ) {
  var this_country = document.createElementNS(XUL_NS,'menuitem');
  this_country.setAttribute( 'label', country );
  this_country.setAttribute( 'value', CountryCodes[ country ] );
  docfrag.appendChild( this_country );
}
$('countryCodePopup').appendChild( docfrag );
$('countryCode').setAttribute( 'selectedIndex', 0 );

我的XUL看起来像这样:

 <menulist id="countryCode">
    <menupopup id="countryCodePopup"></menupopup>
 </menulist>

但是,当我在页面上运行它时,菜单项会正确创建,但菜单的第一个元素不会被选中。我试图在其中一个字段上设置一个选定的属性,但结果是一样的。我在这里缺少什么?

谢谢! 卢卡

更新:事实证明,我错误地设置了selectedIndex。应该这样做:          $('countryCode')。selectedIndex = 10;

1 个答案:

答案 0 :(得分:2)

试试这样:

 document.getElementById("countryCode").selectedIndex = 10;

供参考,请检查: https://developer.mozilla.org/en/XUL_Tutorial/Manipulating_Lists

相关问题