简体   繁体   中英

Call Click Event Once After Element Appears?

I use jQuery 1.6.2. I want to call a click event just for once when that element appears at page. This is my selector:

span[resizer='north'][title=''] :first-child"

This can work for triggering click event:

$("span[resizer='north'][title=''] :first-child").click();

How can I make it work only once or after that element appears on the page?

Answer as per how I understand your last comment: I mean I will call click event only once. Let's assume that there is a button. I will call click event of that button once. I mean I will programmatically click that button.

$('button').click(function() {

    $('span[resizer='north'][title='']:first-child').click();
    $(this).unbind('click');
});

You may use DOMNodeInserted event to detect when new element is inserted dynamically.

var alreadyclicked = false; // variable to check that it will be clicked just once
$(document).bind('DOMNodeInserted', function(e) {
    if (!alreadyclicked){
        $("span[resizer='north'][title=''] :first-child").click();
        alreadyclicked = true;
    }
});

Update

The DOMNodeInserted event is deprecated along with other mutation events . Some browsers support it, but looks like this won't last long.

You can use mutation observers instead to keep track of changes in DOM

var alreadyclicked = false;
var observer = new MutationObserver(function(mutations, observer){
            //if new nodes were added
            if( mutations[0].addedNodes.length && !alreadyclicked )
                $("span[resizer='north'][title=''] :first-child").click();
                alreadyclicked = true;

        });
observer.observe( document, { childList:true, subtree:true });

Use a custom event, with a delegated handler attached using .one().

An event has 2 components, triggering and handling. Don't focus on how many times it's triggered, focus on how many times it's handled.

$("document").one("myclick", "span[resizer='north'][title=''] :first-child", function(e) {
  do something...;
  $(this).click(); //if you actually need the "click"
});
$("span[resizer='north'][title=''] :first-child").trigger("myclick");

This example will mean it's "handled" one time. The other answers on here can be used to ensure it's triggered when the element is added if it's after document ready.

You could also use a pub/sub which would make it even easier. Then you just have to trigger your custom event from the ajax or whatever code that would add the element and not worry about specifically targeting the element. Last line of code in the subscription would be to unsubscribe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM