使用jquery排除具有特定类的元素

时间:2014-04-19 20:35:39

标签: javascript jquery html

在产品页面上点击图片或链接时,我试图在警告框中获取产品名称。但是现在还有一个立即购买按钮,如果点击该按钮,它当前也会提供弹出警报。我想用jquery排除它。这是我要去的地方

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
    $(".item").click(function (event) {
        var href = $('a', this).attr("href");
        var target = $('a', this).attr("target");
        var text = $(this).find('.product-name').text();
        event.preventDefault();
        alert(text);
        setTimeout(function () {
            window.open(href, (!target ? "_self" : target));
        }, 300);
    });
});
</script>

<li class="item">

<a href="product1.php" title="Sample Product Name" class="product-image">
    <span class="sale-item">Sale!</span>
    <div class="cat-mouseover"></div>
    <img src="/images/product1.png" alt="Sample Product Name">
</a>
<h2 class="product-name"><a href="product1.php" title="Sample Product Name">Sample Product Name</a></h2>
<div class="price-box">

    <p class="old-price">
        <span class="price-label">For:</span>
        <span class="price" id="old-price-426">&nbsp;199,-</span>
    </p>

    <p class="special-price">
        <span class="price-label"></span>
        <span class="price" id="product-price-426"> Now&nbsp;139,- </span>
    </p>
</div>

<div class="actions">
    <button type="button" title="Buy Now" class="button btn-cart" onclick="setLocation('/checkout/cart/add/uenc/aHR0cDovL3d3dy52aXRhLm5vLw,,/product/426/')"><span><span>Buy</span></span>
    </button>
</div>
</li>

<li class="item">

<a href="product1.php" title="Sample Product Name" class="product-image">
    <span class="sale-item">Sale!</span>
    <div class="cat-mouseover"></div>
    <img src="/images/product1.png" alt="Sample Product Name">
</a>
<h2 class="product-name"><a href="product1.php" title="Sample Product Name">Sample Product Name</a></h2>
<div class="price-box">

    <p class="old-price">
        <span class="price-label">For:</span>
        <span class="price" id="old-price-426"> &nbsp;199,- </span>
    </p>

    <p class="special-price">
        <span class="price-label"></span>
        <span class="price" id="product-price-426"> Now&nbsp;139,- </span>
    </p>
</div>

<div class="actions">
    <button type="button" title="Buy Now" class="button btn-cart" onclick="setLocation('/checkout/cart/add/uenc/aHR0cDovL3d3dy52aXRhLm5vLw,,/product/426/')"><span><span>Buy</span></span>
    </button>
</div>
</li>

http://jsfiddle.net/585BC/

请指教。

2 个答案:

答案 0 :(得分:0)

将它放在回调的顶部:

if ($(event.target).hasClass("btn-cart") || $(event.target).parents(".btn-cart").length !== 0) {
    return;
}

现在,如果“event.target”(=发生点击的地方)有“btn-cart”类或者是“btn-cart”的子项,那么回调的执行将返回。

请参阅更新的小提琴:http://jsfiddle.net/585BC/2/

答案 1 :(得分:0)

如果单击按钮,只需退出事件处理程序:

if(($(event.target).is('.button.btn-cart')) return;
// rest of your code goes here