【问题标题】:How to increment counter with button click in Razor pages如何在 Razor 页面中通过单击按钮来增加计数器
【发布时间】:2021-05-06 00:40:44
【问题描述】:

您好,我尝试将 Jquery 实现到我的 Razor 页面 第一个工作。但我找不到根本原因为什么在 foreach 之后它不起作用。

我的 HTML:

    @foreach(var item in Model.ErrorList)
    {
        <input  type="button" id=@item.ErrorListID value=@item.ErrorName />
        <input type="text" name="Tb+@item.ErrorListID" id="Tb+@item.ErrorListID" value="0" />

    }

工作脚本:

        <script>
            $(document).ready(function(){
             //var counter = $('#TextBox').val();
                $('#AddButton').click( function() {
                    var counter = $('#TextBox').val();
                    counter++ ;
                    $('#TextBox').val(counter);
                });
            });
        </script>

所有按钮的 JQ。一定有什么错误:-(

@foreach (var item in Model.ErrorList)
{
    <script>
    $(document).ready(function(){
        //var counter = $('#TextBox').val();
        $('#@item.ErrorListID').click( function() {
            var counter = $('#Tb+@item.ErrorListID').val();
            counter++ ;
            $('#Tb+@item.ErrorListID').val(counter);
        });
    });
    </script>
}
}

【问题讨论】:

  • 你在最后一个代码 sn-p 的末尾多了一个}
  • 我不使用 Razor,但它可能无法替换字符串中的 @item
  • 试试$('#Tb' + @item.ErrorListID)

标签: jquery razor-pages


【解决方案1】:

使用按钮上的类,您可以解决这个问题。

从每个按钮点击中,您可以定位“下一个”input

@foreach(var item in Model.ErrorList)
{
    <input type="button" class="incrementer" id=@item.ErrorListID value=@item.ErrorName />
    <input type="text" name="Tb+@item.ErrorListID" id="Tb+@item.ErrorListID" value="0" />
}

然后,您只需要一个事件处理程序:

$(document).ready(function(){
    
    $('.incrementer').click( function() {
        let nextInput = $(this).next("input")
        let count = parseInt(nextInput.val()) + 1
        nextInput.val(count)
    });
});

【讨论】:

  • 谢谢你帮了我很多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多