选择除div子项以外的部分

时间:2016-01-23 10:37:41

标签: jquery html css

我在section.artist-info上发了点击事件,但问题是我不会在.core-info上发生点击事件。所以我编写了这个CSS选择器.artist-info:not(.core-info)来选择我需要和不需要的元素。但它没有用。所以现在我的问题是如何选择除{child} section.artist-info以外的div.core-info?这是我的代码:

$("body").on("click", ".artist-info:not(.core-info)", function() {
    if (!$(this).hasClass("preview-lied")) {
        alert("clicked");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <section class="artist-info"> <!-- I'll select this -->
        <div class="toggle-panel"> <!-- I'll select this inclusieve the child -->
            <p>&#9776;</p>
        </div>
        <div class="core-info">  <!-- I won't select this inclusieve the child tags -->
            <h1 class="titel">artist</h1>
            <p class="bold">Top nummers</p>
            <ul class="top-nummers">
                <li>number 1</li>
                <li>number 2</li>
                <li>number 3</li>
            </ul>
        </div>
    </section>
</body>

2 个答案:

答案 0 :(得分:2)

仔细阅读:not。你的代码应该是

$("body").on("click", ".artist-info div:not(.core-info)", function() {
    if (!$(this).hasClass("preview-lied")) {
        alert("clicked");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <section class="artist-info">
        <div class="toggle-panel">
            <p>&#9776;</p>
        </div>
        <div class="core-info">
            <h1 class="titel">artist</h1>
            <p class="bold">Top nummers</p>
            <ul class="top-nummers">
                <li>number 1</li>
                <li>number 2</li>
                <li>number 3</li>
            </ul>
        </div>
    </section>
</body>

当您编写.artist-info:not(.core-info)浏览器时,尝试查找包含课程.artist-info而没有课程.core-info的部分。但是,当您添加.artist-info div:not(.core-info)浏览器时,div.artist-info .core-info正在寻找{{1}}

答案 1 :(得分:1)

您只需将>添加到.artist-info:not(.core-info)

即可

$("body").on("click", ".artist-info:not(> .core-info)", function() {
    if (!$(this).hasClass("preview-lied")) {
        alert("clicked");
    }
});
.artist-info {
 background: gray;
}

.core-info {
  background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="artist-info">
        <div class="toggle-panel"><p>&#9776;</p></div>
        <p class="fa fa-pause fa-2x big-play"></p>
        <div class="core-info">
            <h1 class="titel"></h1>
            <p class="bold">Top nummers</p>
            <ul class="top-nummers">
                <li>number 1</li>
                <li>number 2</li>
                <li>number 3</li>
            </ul>
        </div>
    </section>