简体   繁体   中英

jQuery select links that don't have any JS events linked to them for PJAX to work on links only?

I have a basic shopping website built on WordPress and Woocommerce. Naturally, a lot of the buttons and links have Javascript functions preventing the default behavior of going to the link and doing something else instead. Unfortunately, if I set PJAX to select all $('a') elements, then the AJAX functions (or javascript such as even dropdown) functions would seize to work properly and PJAX would take over and refresh the page.

For example, if I would click on a Bootstrap dropdown link, it would go to the link rather than open the dropdown.

I want to know if there's a way to select elements (using jQuery) that only go to their links and have no JS events listening to them.

Try this demonstration and let me know if it works for your scenario.

HTML:

<a href="#" class="link-with-handler">Link 1</a>
<a href="#">Link 2</a>
<a href="#" class="link-with-handler">Link 3</a>
<a href="#">Link 4</a>
<br>
<br>
<button id="test">Which links have no jQuery click event bound?</button>

jQuery:

$(function() {
    // Assign handler to links with class 'link-with-handler'
    $('.link-with-handler').click(function() { alert('handled'); });

    // Test function
    $('#test').click(function(){
        // Get all links
        var links = $('a');

        // Iterate through links testing each one for the event handler
        $.each(links, function( index, value ) {
            var ev = $._data(value, 'events');
            if (!ev || !ev.click) { 
                alert(value.innerText + ' has no jQuery click handler bound to it.');  
            }
        });
    });
});

http://jsfiddle.net/goq7a6bn/2/

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