简体   繁体   English

jQuery选择器不匹配元素

[英]jQuery selector not matching elements

I have some jQuery that is causing me a little head ache at the moment. 我有一些jQuery,目前让我有点头痛。 It all boils down to how the selector is working. 归结为选择器的工作方式。

I have some HTML in the form of: 我有一些HTML形式:

<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. 如果我使用以下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. 本质上, click是由#master处理的,并且仅在选择器.pagination a与clicked元素匹配时才触发。 This way works if any children/descendants are dynamically added to the page after DOM load. 如果在DOM加载后将任何子代/后代动态添加到页面,则此方法有效。

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. 它将click事件直接附加到“ #master匹配.pagination a后代”,因此,当附加处理程序时,要求元素出现在DOM中。

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. 我现在可以处理链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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