简体   繁体   中英

How to trigger an event for on(event)

I want to trigger an event to execute code wrapped in $('.selector').on('event') .

The selector change just before I trigger the event.
To understand the problem : I have a text on page 1 and the function trigger a click to go to the page 2 (this works btw!). So now I'm on page 2 and I want to trigger a click to execute code in on() method. And this doesn't work.

I've tried many things and nothing works, the only way to execute the code in on() method is to manually click on the selector.

This is the entire code actually :

jQuery(function() {

    // the input field
    $input = jQuery("input[type=\'search\']");
    // clear button
    var $clearBtn = jQuery("button[data-search=\'clear\']"),
        // prev button
        $prevBtn = jQuery("button[data-search=\'prev\']"),
        // next button
        $nextBtn = jQuery("button[data-search=\'next\']"),
        // the context where to search
        $content = jQuery(".search_content"),
        // jQuery object to save <mark> elements
        $results,
        // the class that will be appended to the current
        // focused element
        currentClass = "current",
        // top offset for the jump (the search bar)
        offsetTop = 50,
        // the current index of the focused element
        currentIndex = 0,
        //the current ajaxpage
        currentPage = 1;

    /**
     * Jumps to the element matching the currentIndex
     */
    function jumpTo() {
        if ($results.length) {

            var position,
                $current = $results.eq(currentIndex);

            $results.removeClass(currentClass);
            if ($current.length) {
                $current.addClass(currentClass);
                position = $current.offset().top - offsetTop - 100;
                window.scrollTo(0, position);
            }
        }
    }
    var mark = function() {

        // Read the keyword
        var keyword = $input.val();

        // empty options
        var options = {};

        // Remove previous marked elements and mark
        // the new keyword inside the content
        jQuery(".search_content").unmark({
            done: function() {
                jQuery(".search_content").mark(keyword, options);
                $results = $content.find("mark");
                currentIndex = 0;
                jumpTo();
            }
        });
    };

    function registerClear() {
        $input.on("input", function() {
            searchVal = this.value;
            $content.unmark({
                done: function() {
                    $content.mark(searchVal, {
                        separateWordSearch: true,
                        done: function() {
                            $results = $content.find("mark");
                            currentIndex = 0;
                            console.log(searchVal);
                            console.log("page2");
                            jumpTo();
                        }
                    });
                }
            });
        });

    }
    registerClear();

    /**
     * Clears the search
     */
    $clearBtn.on("click", function() {
        $content.unmark();
        $input.val("").focus();
    });

    /**
     * Next and previous search jump to
     */
    $nextBtn.add($prevBtn).on("click", function() {
        if ($results.length) {
            currentIndex += jQuery(this).is($prevBtn) ? -1 : 1;
            if (currentIndex < 0) {
                currentIndex = $results.length - 1;
            }
            if (currentIndex > $results.length - 1) {
                currentIndex = 0;
            }
            //TODO : - LINK DONE - SEARCH ON EACH PAGE IF THERE ARE OCCURENCE
            if (currentIndex == 0 && jQuery(this).is($nextBtn)) {
                if (confirm("No more instances found! Go to the next page?")) {
                    alert("NEXT PAGE");
                    jQuery("a[data-page=\'2\']").click();

                    jQuery(document).ready(function() {
                        jQuery(".search_content").click();
                    });
                    jQuery(document.body).on("click", ".search_content", mark)
                    registerClear();
                } else {
                    //do nothing
                }
            }
            jumpTo();
        }
    });

});

this is the important part:

    if (currentIndex == 0 && jQuery(this).is($nextBtn)) {
        if (confirm("No more instances found! Go to the next page?")) {
            alert("NEXT PAGE");
            jQuery("a[data-page=\'2\']").click();

            jQuery(document).ready(function() {
                jQuery(".search_content").click();
            });
            jQuery(document.body).on("click", ".search_content", mark)
            registerClear();
        } else {
            //do nothing
        }
    }

What I've tried :

I've search many things on SO.
Since the content on which I trigger the event is loaded via ajax I thought it was because I triggered the event to soon, so I've tried wrapping my code in document.ready, or with setTimeOut function. No results.

I've tried this :

jQuery('#bar')[0].click();

This :

jQuery(document).ready(function(){
    jQuery('#foo').on('click', function(){
         jQuery('#bar').simulateClick('click');
    });
});

jQuery.fn.simulateClick = function() {
    return this.each(function() {
        if('createEvent' in document) {
            var doc = this.ownerDocument,
                evt = doc.createEvent('MouseEvents');
            evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            this.dispatchEvent(evt);
        } else {
            this.click(); // IE Boss!
        }
    });
}

I've tried putting the trigger after the on() method.
I've tried changing the element on which I do the event.
And also changing the event triggered.

Now I feel like I've tried everything, so I am asking for your help please.

$('element_selector').trigger('eventname', param1, param2,...);

这将触发给定事件,如果需要,则参数是可选的

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