我已经在右键单击上实现了上下文菜单。在菜单上,我有一个按钮,按下后会显示console.log("button is clicked");
消息。
我面临的问题是,第一次单击时,我收到消息 1次。 第二次,一次单击,我得到的消息是 2次。 像这样...
下面是我的jquery代码:
$(document).on("contextmenu", function(event) {
if ($(event.target).hasClass("sim-row-edit")) { // sim-row-edit ended
console.log("right click identified");
.....
// no problem in here
// multiple occurance problem coming here
$(".custom-menu li").click(function() {
switch ($(this).attr("data-action")) {
case "firstcase":
var thisDiv = target_element.closest('div');
console.log("Button is clicked");
break;
case "nextcase":
...
$(document).on("mouseup", function() {
$(".selected").removeClass("selected");
$(".custom-menu").hide(100);
});
html代码:
<ul class='custom-menu'>
<li data-action = "first">Clone</li>
<li data-action = "second">Remove</li>
<li data-action = "third">Edit</li>
</ul>
如何摆脱这个问题?
答案 0 :(得分:1)
尝试event.stopPropagation()
:
$(".custom-menu li").click(function(e) {
e.stopPropagation();
switch ($(this).attr("data-action")) {
case "firstcase":
var thisDiv = target_element.closest('div');
console.log("Button is clicked");
break;
case "nextcase":
...
答案 1 :(得分:1)
使用.unbind()
,可以肯定使用...
答案 2 :(得分:0)
$(document).on("contextmenu", function(event) {
if ($(event.target).hasClass("sim-row-edit")) { // sim-row-edit ended
console.log("right click identified");
.....
// no problem in here
// unbind click handler to avoid multiple occurance problem
$(".custom-menu li").unbind('click');
$(".custom-menu li").click(function() {
switch ($(this).attr("data-action")) {
case "firstcase":
var thisDiv = target_element.closest('div');
console.log("Button is clicked");
break;
case "nextcase":
...
$(document).on("mouseup", function() {
$(".selected").removeClass("selected");
$(".custom-menu").hide(100);
});
只需取消绑定previos click处理程序,然后再次添加处理程序即可。从jQuery 3.0开始,.unbind()
已被弃用。它已被.off()