jQuery: How to detect if an element is not clicked?

坚强是说给别人听的谎言 提交于 2019-12-04 14:04:54

问题


I'd like to know if it is possible to detect if an element is not clicked. This is the code I have:

$("#mpElement").myFeature({
            .........
            .........
            .........
    afterDo: function() {
        // This if-else statement has to go inside "when not clicked" condition. 
        // Not sure how to do this...
        if($(".myButton").last().hasClass("selected")) {
            $(".myButton").first().addClass("selected");
            $(".myButton").last().removeClass("selected");
        } else {
            $(".selected").removeClass("selected").next().addClass("selected");
        }
        $(".myButton").on("click", function(){
            $(".myButton").removeClass("selected");
            $(this).closest(".myButton").addClass("selected"); 
        });
    }
});

You will notice $(".myButton").on("click", function(){ for detecting click event. I'd like to put the if-else statements above this function inside when not clicked condition. Not sure how to do this.


回答1:


You can maintain a data property to that element as a click detector.

Example:

<button class="myButton" data-clicked="no">My Button</button>

Here, I set data-clicked=no as initial config.

Within the click event set data-clicked to yes like:

$('.myButton').on('click', function() {
  $(this).data('clicked', 'yes');
});

Now check this data-clicked property like below:

var isClicked = $('.myButton').data('clicked');

if( isClicked == 'yes') {
   // do something
} else {
  // do something else
}


来源:https://stackoverflow.com/questions/12444534/jquery-how-to-detect-if-an-element-is-not-clicked

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