javascript - 从数据属性中动态获取值
问题描述
如何获取和存储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;
}
解决方案
您正在下载按钮中搜索数据属性,而不是在实际存在的输入字段中搜索。
在输入字段中添加一个类/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;
}
推荐阅读
- python - 如何将一行值写入csv文件
- android - 将项目装饰添加到追星族可扩展组
- php - 如何从函数返回值并使用 jquery 发送到 AJAX?
- r - 使用具有不相等条目数的 dcast 重塑数据帧
- java - 如何设置 SSLServerSocket TLS 协商超时?
- python - 如何使用多部分 ContentType 构建 HttpResponse
- java - 操作员 !不能应用于 int
- forms - Xamarin 在 xaml 中形成应用程序外壳背景颜色底部选项卡
- microsoft-cognitive - 表单设计最佳实践
- javascript - 如何根据位置在 Google 地球引擎中对图像集合进行子集化?