【问题标题】:Identifying specific button in a form识别表单中的特定按钮
【发布时间】:2019-02-10 17:56:24
【问题描述】:

所以如果在我的表单中单击一个按钮,我想获得一个特定的值,但不知何故它会监听所有按钮,而不仅仅是我表单中的按钮。

除了下面的 javascript 示例,我还尝试通过调用该类

$('.modifygap').bind('click', function (e) {

但在此示例中,该值未正确设置。

这是我的html:

<button type="button" id="anotherbutton">Another</button>

<form action="editortoken_information" id="showtoken" method="POST">

    <button class="btn btn-outline-secondary" type="submit" name="modifygap" id="modifygap" class="modifygap"
    value="14" data-value="test">14</button>

    <button class="btn btn-outline-secondary" type="submit" name="modifygap" id="modifygap" class="modifygap" 
    value="15" data-value="test">15</button>

</form>

这是我的 javascript 函数:

$(document.getElementById("showtoken")).ready(function () {
    $("button").click(function (e) {
         e.preventDefault();
         document.getElementById('tokenindex').value = this.getAttribute("data-value");
    })
})

我认为只监听特定的 id 只会检测表单中的按钮点击。但由于某种原因,它正在监听所有按钮点击。

【问题讨论】:

  • 两个元素不能有相同的id,id="modifygap"是两次
  • ID 是唯一的
  • 你应该只有一个class属性
  • 如果我的按钮具有相同的 id 并且没有真正通过 id 调用它们,或者我可以不为每个按钮定义一个 id,是否会出现问题?
  • 你应该有唯一的id

标签: javascript html forms button


【解决方案1】:

使用event.target.value获取被点击元素的值。

$(document).ready(() => {
  $('.modifygap').bind('click', function (e) {
    console.log('e', e.target.getAttribute("data-value"))
  });  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="anotherbutton">Another</button>



    <button class="btn btn-outline-secondary modifygap" type="submit" name="modifygap" id="modifygap"
    value="14" data-value="test14">14</button>

    <button class="btn btn-outline-secondary modifygap" type="submit" name="modifygap" id="modifygap" 
    value="15" data-value="test15">15</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2023-03-14
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多