【问题标题】:Nested button inside divdiv内的嵌套按钮
【发布时间】:2018-07-14 18:41:21
【问题描述】:

情况是这样的。我有一个盒子,它是一个 div,其中包含另一个 div,它基本上是一个按钮。单击外框时,它应重定向到产品详细信息页面。当单击框中的按钮时,它应该执行一个 ajax 调用,将该特定项目添加到购物车。

目前,当点击外框时,它会重定向到产品详细信息页面,这是所需的功能。但是,当单击内部按钮时,它会添加到购物车并重定向,而我不希望它重定向而只是添加到购物车。如何实现这个所需的功能?

这是asp.net的代码

@using LaptopMart.Models
@model IEnumerable<LaptopMart.Models.Product>


@{


            ViewBag.Title = "User Index";

}

<h2>title</h2>


@foreach (Product product in Model)
{
<div class="inline">
    <div  class="A" div-product-id ="@product.Id">
        <div class="card">
            <div class="card-head">
                <img src="~/Content/ProductImages/@product.Image" alt="product-image" class="card-product-image">
            </div>
            <div class="card-body">
                <div class="product-details">
                    <span class="product-title">@product.Name</span>
                    <span class="product-price">$<b>@product.Price</b></span>
                </div>
                <div>
                    <div class="btn-sm btn-primary js-add-to-cart" data-product-id="@product.Id" >Add to Cart</div>
                </div>
            </div>

        </div>
    </div>
</div>
}



@section scripts
{
<script>
    $(document).ready(function () {

        $(".A").on("click", function () {
            if ($(this).hasClass("js-add-to-cart")) {
                return;
            }
            else {
                window.location.href = "/user/ProductDetails/" + $(this).attr("div-product-id"); 
            }


        });
        $(".js-add-to-cart").on("click",
            function () {
                var button = $(this);

                $.ajax({
                    url: "/api/user/AddToCart/" + button.attr("data-product-id"),
                    method: "GET",
                    success: function () {

                        window.setTimeout(function () {
                            bootbox.hideAll();
                        }, 1000);

                        bootbox.alert("This has been added to cart");

                    }
                });

            });


    });


</script>
}

【问题讨论】:

标签: javascript jquery html asp.net twitter-bootstrap


【解决方案1】:

在处理内部div 的点击事件的函数中,通过在事件上调用event.stopPropagation() 来阻止事件传播到外部div:

function clickHandler(event) {
  event.stopPropagation();

  // Do your other stuff like Ajax calls
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 2016-09-03
    • 1970-01-01
    • 2015-11-05
    • 2013-06-27
    • 2020-04-20
    • 2012-10-30
    • 1970-01-01
    相关资源
    最近更新 更多