【问题标题】:jQuery script on button is not working按钮上的 jQuery 脚本不起作用
【发布时间】:2018-06-26 11:17:09
【问题描述】:

我认为脚本不起作用,因为一旦我按下网站上的按钮,我的控制器就没有运行。一旦我按下按钮,什么也没有发生。 附上相关代码。我很确定问题出在我的脚本上。

我的脚本:

    <script>
    $("#btn_add").click(function(event)
    {
        event.preventDefault();
        var url = '@Url.Action("AddToCart", "Cart", new {idinput = "IDINPUT", amount = "THEAMOUNTER"})';
        url = url.replace("THEAMOUNTER", $("#amounter").val());
        url = url.replace("IDINPUT", $(this).data("id"));
        window.location.href = url;
    });
</script>

html代码中的相关部分:

@foreach (var product in Model)
        {

            <figure class="portfolio-item col-md-4 col-sm-6">
                <img src="~/images/@product.Picture" class="img-responsive" />
                <div class="product-details">

                    <div class="form-group">
                        <label>Enter amount</label>
                        <div class="col-md-10">
                            <input type="text" id="amounter" />
                        </div>
                    </div>
                    <div>
                        <a id="btn_add" href="" data-id=@product.Id class="btn btn-info btn-lg" style="margin-left:60px">
                            <span class="glyphicon glyphicon-shopping-cart"></span> Add to cart
                        </a><br />

【问题讨论】:

  • 重复的id 属性是无效的 html - 请改用类名
  • 您在浏览器控制台中遇到什么错误?
  • 没有错误...只是没有任何反应。我无法关注您的第一条评论。您的意思是我应该将“#btn_add”替换为“.btn btn-info btn-lg”吗?
  • 删除id="btn_add",然后使用其中一个现有的类名(或添加一个额外的类名——比如“添加”,然后使用$(".add").click(...

标签: jquery html asp.net asp.net-mvc


【解决方案1】:

给重复的按钮一个类,而不是使用重复的ids。比如.Mybtn

<a href="" data-id='@product.Id' class="btn btn-info btn-lg Mybtn" style="margin-left:60px">

将您的点击处理程序放在文档就绪部分。

<script>
    $(function(){
        $(".Mybtn").click(function(event)
        {
            event.preventDefault();
            var url = '@Url.Action("AddToCart", "Cart", new {idinput = "IDINPUT", amount = "THEAMOUNTER"})';
            url = url.replace("THEAMOUNTER", $("#amounter").val());
            url = url.replace("IDINPUT", $(this).data("id"));
            window.location.href = url;
        });
    });
</script>

【讨论】:

  • 这与OP的问题无关(它只是无效的html)
  • 我将您的代码复制到我的代码中。但问题是一样的。按下按钮后浏览器没有任何反应..
  • @TalRofe,当您在 Html 中执行 data-id=@product.Id 时,缺少引号。
猜你喜欢
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多