点击按钮点击右键菜单 - jQuery

时间:2017-04-24 07:21:28

标签: javascript jquery html css

以下是我的jQuery代码,除了第一次点击外,它正常工作。我希望在第一次单击时禁用右键单击,但不知何故,首次单击不会禁用右键单击,但在切换后工作。让我知道我在这里做错了什么。

jQuery代码 -

let $document = $(document);
    $document.ready(() => {
        let toggleValue = true;
        $('.btn-toggle').on('click', () => {
            $document.on('contextmenu', (e) => {
                if(toggleValue) {
                    e.preventDefault();
                }
            });
        toggleValue = !toggleValue;
    })
})

HTML代码 -

<h3>Toggle right click menu on button click</h3>

<button class="btn-toggle">Toggle Right Click</button>

JSFIDDLE - https://jsfiddle.net/mLm096o4/

3 个答案:

答案 0 :(得分:1)

您反复重新分配点击处理程序 - 尝试只指定一次点击处理程序。

let $document = $(document);        
    $document.ready(() => {
        let toggleValue = true;
        $document.on('contextmenu', (e) => {
                if(toggleValue) {
                    e.preventDefault();
                }
            });

        $('.btn-toggle').on('click', () => {            
            toggleValue = !toggleValue;
        })
    })

答案 1 :(得分:1)

从事件监听器中删除代码以处理右键单击 Toggle Right Click 按钮。

const $document = $(document);

$document.ready(() => {
  let toggleValue;

  $('.btn-toggle').on('click', () => {
    toggleValue = !toggleValue;
  });

  $document.on('contextmenu', (e) => {
    if (toggleValue) {
      e.preventDefault();
    }
  });
});

此外,您可以将let $document = $(document);更改为const $document = $(document);,因为您不会为此变量指定不同的值(至少您不应该这样做)。

修改:根据评论进行了更新。

答案 2 :(得分:0)

只需使用if(toggleValue === false)代替if(toggleValue)

&#13;
&#13;
let $document = $(document);		
$document.ready(() => {
  let toggleValue = true;
  $('.btn-toggle').on('click', () => {
    $document.on('contextmenu', (e) => {
      if(toggleValue === false) {
        e.preventDefault();
      }
    });
    toggleValue = !toggleValue;
  })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Toggle right click menu on button click</h3>

<button class="btn-toggle">Toggle Right Click</button>
&#13;
&#13;
&#13;