如何避免鼠标多次调用

时间:2014-12-30 08:27:42

标签: javascript jquery

我在mouseup上有一个功能。当用户单击并选择文档中的某些文本并单击保存按钮时,我需要保存该文本。

当用户点击而不保存按钮时(无论何时),我的功能是在用户点击保存文本按钮后继续调用。

如何避免这种情况?

这是我的js:

$('.documentpage').mouseup(function (e) {
    e.stopPropagation();
    if ($.trim(window.getSelection().toString()).length) {
        setTimeout(function () {
            //delaying to get selection
            if (rangy.supported && classApplierModule && classApplierModule.supported) {
                boldRedApplier = rangy.createCssClassApplier('');
                currentSelection = boldRedApplier.validateSelection();

                valid = that.isValidText(currentSelection);

                if (!valid) {
                    currentSelection.contents().unwrap();
                    that.clearTextSelection();
                    return;
                }

                if (valid.status) {
                    that.saveTextButton.show();
                    that.saveTextButton.click(function () {
                        that.onValidSelection(currentSelection); //it calls multiple tiems, whatver the user selected on valid.
                    })

                }

            }
        }, 100);
    }
});

1 个答案:

答案 0 :(得分:1)

您的问题似乎是每次有mouseup事件时尝试在函数内添加事件侦听器。尝试单独设置that.saveTextButton.click(function (),然后只显示mouseup上的按钮。我不得不在没有代码所需的所有变量的情况下摆弄它,但你应该明白这一点:



var valid =true;
//var valid =false;

$('.documentpage').mouseup(function(e){
                e.stopPropagation();
                if($.trim(window.getSelection().toString()).length) {
                    setTimeout(function () {
                    //delaying to get selection
                      
                      //..other code that checks stuff...
                      
                      if(valid){ 
                           $('#saveTextButton').show();

                      }                      
                    }, 100);
                } 
});


$('#saveTextButton').click(function(){
  
      alert('function called');
  
});

.documentpage{
 height:100px;
  width:1000px;
  background-color:#cccccc;
  }

#saveTextButton{
  display:none;
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="documentpage">this is some test text</div>
<input type="button" id="saveTextButton" value="Push me"></input>
&#13;
&#13;
&#13;