如何对listitem做出反应,并为每个listitem添加上下文菜单? [英] How to react on listitem double click and to add context menu for each listitem?
问题描述
在我的xul中有 listbox
元素。 listitem
元素会动态添加。
我怎么能:
- 在每个
listitem
? - 为每个
listitem
? $ b
在 listitem
的创建过程中,我知道每个添加的记录的唯一id(数字)。理想情况下,当双击函数被调用,并且当选择上下文菜单项时,我应该得到这个id(它不应该是用户可见的)。方案
事件泡泡这意味着您可以在< listbox>
元素上注册您的事件处理程序。 event.target
允许您找到< listitem>
元素:
listbox.addEventListener(dblclick,function(event)
{
var target = event.target;
while(target& target.localName!=listitem)
target = target.parentNode;
if(!target)
return; // Event target isn'列表项目
alert(target.getAttribute(recordId));
},false);
假设您已经添加了 recordId
属性添加到列表项目之前。
事情的工作方式与上下文菜单相似(你添加一个 context =... 属性添加到
< listbox>
),区别在于上下文菜单通常在菜单的 popupshowing
事件。这个事件的目标是上下文菜单,所以它不能帮你找到列表项。但是,有一个
menupopup.triggerNode()
属性(现在已经被弃用的 document.popupNode
替代),可以让你完成这项工作:
menu.addEventListener(popupshowing,function(event)
{
var target = event.target.triggerNode ;
while(target& target.localName!=listitem)
target = target.parentNode;
if(!target)
return event.preventDefault() ; //不显示没有列表项的上下文菜单
alert(target.getAttribute(recordId));
},false);
I have listbox
element in my xul. listitem
elements are added there dynamically.
How can I:
- react on double click on each
listitem
? - implement context menu for each
listitem
?
During listitem
s creation, I know unique id (numeric) of each record added there. Ideally when double click function is called and when context menu item is chosen, I should get this id (and it shouldn't be visible to the user).
Events bubble which means that you can register your event handler on the <listbox>
element. event.target
allows you to find the <listitem>
element:
listbox.addEventListener("dblclick", 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.getAttribute("recordId"));
}, false);
This assumes that you've added recordId
attributes to your list items before adding them to the list.
Things work similarly with context menus (you add a context="..."
attribute to the <listbox>
), with the difference that context menus are usually initialized in the menu's popupshowing
event. The target of this event is the context menu itself so it doesn't help you find the list item. However, there is a menupopup.triggerNode()
property (the modern alternative to the deprecated document.popupNode
) that lets you do the job:
menu.addEventListener("popupshowing", function(event)
{
var target = event.target.triggerNode;
while (target && target.localName != "listitem")
target = target.parentNode;
if (!target)
return event.preventDefault(); // Don't show context menu without a list item
alert(target.getAttribute("recordId"));
}, false);
这篇关于如何对listitem做出反应,并为每个listitem添加上下文菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!