嵌套子元素上的上下文菜单也显示父上下文菜单

我有多个DOM元素和上下文菜单。 当一个元素是另一个元素的子元素并且我调用内部子元素的上下文菜单时,我也会看到父元素的上下文菜单。 这是使用jquery-ui.contextmenu插件实现的。

有没有办法配置插件以防止显示父菜单或我将不得不手动处理所有点击事件并过滤它们所以我只显示我想要的菜单?

以下是我的代码:

HTML:

 
Outer Child
Inner Child

CSS:

 .outer-child { position: absolute; top: 0px; left: 0px; width: 200px; height: 200px; border: 1px solid red; background: green; } .inner-child { position: absolute; top: 50px; left: 50px; width: 100px; height: 100px; border: 1px solid blue; background: yellow; } 

JavaScript的:

 // create context menu on outer child $("#outer-child").contextmenu({ menu: [ {title: "This is the Outer Menu", cmd: "outer-menu"} ], select: function(event, ui) { alert("select " + ui.cmd + " on " + ui.target.text()); } }); // create context menu on inner child $('#inner-child').contextmenu({ menu: [ {title: "Inner Menu", cmd: "inner-menu"} ], select: function(event, ui) { alert("select " + ui.cmd + " on " + ui.target.text()); } }); 

你可以在这里找到一个jsfiddle演示。 ( 右键单击内框并查看上下文菜单

您可以通过在子元素的beforeOpen事件中调用event.stopPropagation()方法来解决此问题。

 // create context menu on outer child $("#outer-child").contextmenu({ menu: [{ title: "This is the Outer Menu", cmd: "outer-menu" }], select: function(event, ui) { alert("select " + ui.cmd + " on " + ui.target.text()); }, }); // create context menu on inner child $('#inner-child').contextmenu({ beforeOpen: function(event, ui) { event.stopPropagation(); }, menu: [{ title: "Inner Menu", cmd: "inner-menu" }], select: function(event, ui) { alert("select " + ui.cmd + " on " + ui.target.text()); } }); 
 .outer-child { position: absolute; top: 0px; left: 0px; width: 200px; height: 200px; border: 1px solid red; background: green; } .inner-child { position: absolute; top: 50px; left: 50px; width: 100px; height: 100px; border: 1px solid blue; background: yellow; } 
      
Outer Child
Inner Child