Javascript 从数据属性中动态获取值

Javascript 从数据属性中动态获取值,javascript,forms,mustache,Javascript,Forms,Mustache,如何获取和存储数据id属性的值?它里面的值在单击按钮时会发生变化,因此我需要一个方法在它变化时获取值。我已经尝试了document.getelementbyid/name/value,但是我得到了唯一的方法,即从第一次单击按钮时获取存储的值。我现在使用的方法$(this).data('id')不返回任何内容。谢谢 胡须文件: <td> <form id="Form" action="./downloaddoc" method="GET"> <

如何获取和存储
数据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>

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

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

我看不到单击时更新属性值的位置。只有使用相同的方法(如$(元素)更新属性时,该方法才会起作用。数据('id',值),如果使用此$(元素),则该方法将不起作用。attr('data-id',值)编辑了我的标题,因为我看到它可能会混淆的位置。我有多个具有唯一数据id的按钮,但是当我单击一个按钮然后单击另一个按钮时,第二个按钮将返回第一个按钮的数据id。这就是我的问题@avcsp请发布一篇文章来说明这个问题。也许把你的代码转换成一个可运行的代码段。这个在你的方法中代表的是按钮,而不是输入字段
<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>
$(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;
}