从数据属性动态获取值

Get dynamically value from data attribute

如何获取和存储 data-id 属性的值?它里面的值在单击按钮时会发生变化,因此我需要一种方法来获取值发生变化时的值。我试过 document.getelementbyid/name/value 但我得到的唯一值是从第一次单击按钮时存储的值。我现在用的方法$(this).data('id') returns 没什么。谢谢

小胡子文件:

<td>
    <form id="Form" action="./downloaddoc" method="GET">
        <input type="hidden" name="p" value="download"/>
        <input type="hidden" name="fileid" data-id="{{file_id}}"/>
        <input class="button download_button" type="submit" value="Download">
    </form>
</td>

js:

$(document).on('click', '.download_button', download_doc);
function download_doc(event) {
    event.preventDefault();
    var id = $(this).data('id');
    console.log(id);
    window.location.href = window.location.href + '?p=download&id=' + fileid;
}

您是在下载按钮中搜索数据属性,而不是在它实际存在的输入字段中搜索。

在输入字段中添加一个 class/id,以便您可以找到它。

当您单击按钮时找到最接近的表单,然后找到包含文件 ID 的输入字段并从中提取文件 ID。

<td>
  <form id="Form" action="./downloaddoc" method="GET">
    <input type="hidden" name="p" value="download"/>
    <!-- Added  a class to the input field -->
    <input type="hidden" name="field" class="input-download-file" data-id="{{file_id}}"/>
    <input class="button download_button" type="submit" value="Download">
  </form>
</td>

Javascript:

$(document).on('click', '.download_button', download_doc);
function download_doc(event) {
  event.preventDefault();

  // Find the closest form
  var form = $(this).closest('form');

  // Find the input field which constains the download file id
  var input = $(form).find(".input-download-file");

  // Get the file id
  var id = $(input).data('id');
  console.log(id);
  window.location.href = window.location.href + '?p=download&id=' + fileid;
}