首页 > 解决方案 > 从数据属性中动态获取值

问题描述

如何获取和存储data-id属性的值?它里面的值在按钮点击时会改变,所以我需要一个方法来获取它改变的值。我已经尝试过 document.getelementbyid/name/value 但我得到的唯一值是从第一个按钮单击中存储的值。我现在使用的方法$(this).data('id')没有返回任何内容。谢谢

胡子文件:

<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;
}

标签: javascriptformsmustache

解决方案


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

在输入字段中添加一个类/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;
}

推荐阅读