简体   繁体   中英

jQuery selector not matching elements

I have some jQuery that is causing me a little head ache at the moment. It all boils down to how the selector is working.

I have some HTML in the form of:

<div id="master">
    <div class="row">
        <div class="medium-6 columns">
            <div class="medium-6 right columns">
                <div class="pagerContent">
                    <div class="pagination">
                        <div class="page">
                            <ul>
                                <li>
                                    <a href="#">
                          ......
etc.

Which contains a bunch anchor tags which from part of my navigation.

If I use the following jQuery.

$('#master').on('click', '.pagination a', function (event) {

    -- code --

});

It works, but if I use

$(".pagination a", "#master").on('click', function (event) {

    -- code --

});

It does not.

Your two examples are subtly different.

This, uses deferred event handling.

$('#master').on('click', '.pagination a', function (event) {

    -- code --

});

Essentially the click is handled by #master and only fires when the selector .pagination a is matched by the clicked element. This way works if any children/descendants are dynamically added to the page after DOM load.

This, does not:

$(".pagination a", "#master").on('click', function (event) {

    -- code --

});

It attaches the click event directly to "descendants of #master matching .pagination a " and as such requires that the elements are present in the DOM when the handler is attached.

Hi and thanks for everyone replies not this. I was still having difficulties getting this to work, so I have tried a different way which does work for me.

For each of the link tags, I have defined a specific class as an identifier so

<a href="#"></a>

became

<a href="#" class="myFirstLink"></a>

then using

$(document).on("click", "myFirstLink", function (event) {
        alert("Hi," + event.target.href + " clicked");
    });

I am now able to process the links.

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