【问题标题】:onClick only works for first button in tableonClick 仅适用于表格中的第一个按钮
【发布时间】:2016-11-05 14:53:32
【问题描述】:

我正在尝试制作一个动态表格,其中表格中的每一行都有一个“修改”按钮,该按钮会弹出一个模式,其中将有一个请求信息的表单。

这是我当前的 CSHTML 代码:

<body>
    <div id="container">
        <h1>Fingerprint Tool</h1>
        <form id="userIdForm" method="post">
            Type in your UserId: <input name="userId" type="number" id="formUserId" />
            <input type="submit" />
        </form>

        @if (Model != null)
        {
            <h2>List of Fingerprints for user</h2>
            <div id="tableDiv">
                <table class="fingerprintTable">
                    <thead>
                        <tr>
                            <th>User ID</th>
                            <th>Fingerprint ID</th>
                            <th>FingerprintGrant ID</th>
                            <th>PaymentType ID</th>
                            <th>Fingerprint</th>
                            <th>IsDeleted</th>
                            <th>Status ID</th>
                            <th>Created Date</th>
                            <th>Updated Date</th>
                            <th>Modify</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var fingerprint in Model.Fingerprints)
                        {
                            <tr>
                                <td id="userId">@fingerprint.UserId</td>
                                <td id="fingerprintId">@fingerprint.FingerprintId</td>
                                <td id="fingerprintGrantId">@fingerprint.FingerprintGrantId</td>
                                <td id="paymentTypeId">@fingerprint.PaymentTypeId</td>
                                <td id="fingerprint">@fingerprint.Fingerprint</td>
                                <td id="isDeleted">@fingerprint.IsDeleted</td>
                                <td id="fingerprintStatusId">@fingerprint.FingerprintStatusId</td>
                                <td id="createdDate">@fingerprint.CreatedDate</td>
                                <td id="updatedDate">@fingerprint.UpdatedDate</td>
                                <td><button id="modifyButton" onclick="modifyFingerprintInfo(@fingerprint.FingerprintId);">Modify</button></td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>

            <div id="myModal" class="modal">

                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close">x</span>
                    <p id="modalHeader"></p>
                </div>

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

这是我的 JS 文件:

    window.onload = function() {
        $(".modifyButton")
        .click(function() {
            modifyFingerprintInfo($(this).data("fpid"));
        });
    }

    function modifyFingerprintInfo(fingerprintId) {
    // call updateStatus hermes endpoint

    // Get the modal
    var modal = document.getElementById("myModal");
    // Get the button that opens the modal
    var btn = $(".modifyButton");
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    // When the user clicks on the button, open the modal 

    // When the user clicks on <span> (x), close the modal
    span.onclick = function () {
        modal.style.display = "none";
    }
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target === modal) {
            modal.style.display = "none";
        }
    }
    $("#modalHeader").text("Update the status of FingerprintId " + fingerprintId);

}

这是我的 CSS 代码:

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

#container {
    width: 100%;
    position: absolute;
    left: 4px;
}

问题是当我单击每一行中的修改按钮时,我第一次单击时没有任何反应,然后第二次它起作用了,但仅适用于第一行中的第一个按钮。最重要的是,例如,如果我单击第 4 行修改按钮,什么都不会发生,但是当我单击第 1 行修改按钮时,它会打印出第 4 行的详细信息。

我不知道发生了什么,所以任何帮助将不胜感激!

【问题讨论】:

    标签: jquery html css razor model-view-controller


    【解决方案1】:

    考虑到您的主要意图,您打算在动态表上找到一个按钮,因此为了能够执行此操作,您的 id 也需要是动态的。

    假设@fingerprint.UserId 是唯一的,不会在您的列表中重复出现。有了这个唯一标识符,您可以执行以下操作:

    <button id="modifyButton_@fingerprint.UserId">Modify</button>
    

    因此,您需要更新函数以正确触发并从按钮 ID 中提取唯一标识符。一个可能的解决方案是使用 jquery 选择器来创建这种动态。

    参考:https://api.jquery.com/id-selector/

    参考:https://api.jquery.com/attribute-starts-with-selector/

    $( "button[id^='modifyButton_']" ).(function);
    

    考虑到您的函数被正确触发,现在您可以从按钮 id 中提取表中数据的引用。

    参考:https://api.jquery.com/click/

    var userId = $(this).attr("id").replace("modifyButton_"); 
    

    考虑到此解决方案,您还可以使用动态内容填充您的模式,从而改善用户体验。

    我希望它可以帮助您改进您的解决方案。如有疑问,请告诉我。

    【讨论】:

      【解决方案2】:

      您可以使用class 而不是id 来识别多个元素。 id 属性旨在用于单个元素,如果多个元素具有相同的 id,则只会选择 1 个。

      其次,您不想在点击事件处理程序中设置点击事件处理程序。让我们一次性完成。

      我看到你用jQuery标记了这个问题,所以你可以使用:

      <button class="modifyButton" data-fpid="1111">Modify</button>
      
      $(".modifyButton").click(function() {
          $("#modalHeader").text("Update the status of FingerprintId " + $(this).data("fpid");
          $("#myModal").show();
      });
      

      这表明通过使用id,只有第一个触发:

      $("#button").click(function() {
        alert($(this).text());
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <button id="button">Clicked button ONE</button><br /><br />
      <button id="button">Clicked button TWO</button><br /><br />
      <button id="button">Clicked button THREE</button>

      这表明通过使用class,它们中的任何一个都会触发:

      $(".button").click(function() {
        alert($(this).data("fpid"));
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <button class="button" data-fpid="111">Clicked button ONE</button><br /><br />
      <button class="button" data-fpid="222">Clicked button TWO</button><br /><br />
      <button class="button" data-fpid="333">Clicked button THREE</button>

      【讨论】:

      • 使它成为一个类并没有任何影响。另外,我刚刚附加了一个onclick 处理程序,它实际上做了同样的事情。
      • 好的,很高兴知道。但是,通过将其更改为 class,并没有真正改变。我使用 onclick 处理程序的原因是因为这样我可以轻松地将参数传递给 JS 方法。
      • 好的,在这种情况下我们使用data-fpid。所以我将编辑代码以显示可以吗?
      • 所以当我尝试只做警报时,它起作用了。但是现在在我的modifyFingerprintInfo 方法中,模态不会弹出。你知道为什么吗?
      • 这是一个快速的 jsfiddle,如果您愿意,可以查看和编辑。这一切都在点击事件处理程序中完成:jsfiddle.net/L47b7jpm
      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2019-01-12
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      相关资源
      最近更新 更多