How to react on listitem double click and to add context menu for each listitem?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 04:34:57

问题


I have listbox element in my xul. listitem elements are added there dynamically.

How can I:

  1. react on double click on each listitem?
  2. implement context menu for each listitem?

During listitems 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).


回答1:


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);


来源:https://stackoverflow.com/questions/8840919/how-to-react-on-listitem-double-click-and-to-add-context-menu-for-each-listitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!