【问题标题】:find out which button was pressed in the foreach loop找出在 foreach 循环中按下了哪个按钮
【发布时间】:2019-04-28 18:35:17
【问题描述】:

我将他的笔记列表返回给用户,当然,它们的数量可能不定。 当文本超过 80 个字符时,我会创建按钮。

通过单击此按钮,我想在其他按钮中单击并找出有关其父 div 的所有信息。我该怎么做?

<div class="d-flex flex-wrap">
        @foreach (var item in ViewBag.UserTodoList)
        {
            <div class="card" style="width: 32%; margin-left: 1%; margin-top:1%">
                <div class="card-body">
                    <h5 class="card-title">@item.Name</h5>
                    @if (item.Body.Length > 80)
                    {
                        <p class="card-text">@item.Body.Substring(0, 80)...</p>
                        <button class="btn btn-info" id="1234">Прочитать</button>
                    }
                    else
                    {
                        <p class="card-text">@item.Body</p>

                    }

                    <a asp-controller="ToDo" asp-action="DeleteTodos" asp-route-todoId="@item.Id" class="btn btn-primary">Удалить</a>
                </div>
            </div>
        }
    </div>

【问题讨论】:

  • 您可以使用数据属性将当前迭代数据项附加到按钮,然后按照建议在按钮的单击处理程序中获取该按钮的全部数据。这就是你所追求的吗?

标签: javascript c# jquery asp.net-core razor


【解决方案1】:

类似这样的:

const buttons = Array.from(document.querySelectorAll('.card .btn'));

function handleClick() {
    const parent = this.parentNode; // here is parent
    console.log(parent) // lets log it to console
}

buttons.forEach((button) => { button.addEventListener('click', handleClick);})

顺便说一句,您应该为按钮添加独特的类。通过querySelectorAll 或getElementsByClassName 获得它们会更容易

【讨论】:

    【解决方案2】:

    我不是这方面的专家(也是新的),但我会怎么做是添加 button 像 ErrorClass 这样的类,然后在 script 里面我会做

    $('.ErrorButton').click(function() {
        var parent = this.parent(); // With this you get parent div container
    });
    

    【讨论】:

    • 感谢您的评论,但我可以有很多按钮,根据我的经验,您编写的方式仅适用于第一个按钮
    • 查看编辑。这样你就可以有多个按钮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2017-05-22
    • 2019-08-07
    • 1970-01-01
    • 2020-11-18
    • 2016-09-16
    相关资源
    最近更新 更多