仅在单击时将 jQuery 效果添加到 HTML 元素父级

adding a jQuery effect only to the HTML element parent onclick

本文关键字:添加 HTML 元素 单击 jQuery      更新时间:2023-09-26

我想将jquery效果'flash'应用于html元素"item_add"的父元素"simpleCart_shelfItem"。这是为了表明用户已将商品添加到购物车。我通过引用父级来做到这一点,因为有许多"simpleCart_shelfItem"实例,我希望效果只发生在单击的实例上。我一直在阅读this,从我收集的内容来看,我不能内联onClick事件,因为this将是全局的,而不是引用函数中的元素。这是我所拥有的:

爪哇语

$(".item_add").onclick = highlight;
function highlight(){
  $(".item_add").parent().effect("highlight", {}, 750);
};

.HTML

<div class="simpleCart_shelfItem">
                <div class="image"><img src="css/graphics/jpeg/saw.jpg" alt="Hacksaw" height="75" width="75" /></div>
                <h2 class="item_name">Hacksaw</h2>
                <span class="item"><img src="css/graphics/jpeg/cart.jpg" alt="Shopping Cart" height="20" width="19" />
            Items in Cart: <b class="simpleCart_quantity"></b></span> 
                <div class="description"><p>Quality metal hacksaw and 24 tooth blade.</p><p class="p_height">Your going to need some way of cutting that pipe. Good for the toolbox.</p></div>
                <a class="add_products" href="cart.html">Go to Cart</a>
                <a class="add_products" href="products.html" title="Add Items">Add More Items</a>
                <span class="gst">(Inc. GST)</span>
                <span class="item_price">$24.95</span>
                <input class="item_quantity" value="1" type="text">
                **<a href="javascript:;" class="item_add" onclick="highlight();">Add</a>**
            </div><!--end of simpleCart_shelfItem-->
$(".item_add").click(function() {
    $(this).parent().effect("highlight", {}, 750);
});

在上面的示例中,this 是指单击的元素。我不知道你所说的this是全球性的到底是什么意思,但你错了:-)(或者我误会了你)。

从 http://www.quirksmode.org/js/this.html:

在 JavaScript 中,这总是指我们正在执行的函数的"所有者",或者更确切地说,是指函数作为方法的对象。

查看演示