
本文旨在解决在使用 jQuery 动态生成包含隐藏 input 元素的 div 时,点击不同 div 获取到相同 ID 的问题。通过事件委托和查找父元素的方式,确保每次点击都能准确获取到对应 div 中 input 元素的正确值。
在使用 jQuery 动态生成 HTML 元素时,尤其是涉及到事件处理和数据获取,很容易遇到一些问题。本文将详细介绍如何在使用 jQuery 动态生成包含隐藏 input 元素的 div 列表时,正确获取到被点击 div 对应的 ID 值。
问题描述
假设你有一个动态生成的用户列表,每个用户都包含一个隐藏的 input 元素,用于存储用户的 ID。当点击某个用户时,你需要获取该用户的 ID。然而,由于所有动态生成的 input 元素都具有相同的 name 属性,直接使用 $(“input[name=’id_utt’]”).val() 获取到的总是第一个 input 元素的值,而不是当前点击的那个。
解决方案:事件委托和查找父元素
解决这个问题的关键在于使用事件委托和查找父元素的方式。
事件委托: 将事件监听器绑定到父元素上,而不是直接绑定到动态生成的子元素上。这样可以确保即使子元素是动态生成的,事件监听器也能正常工作。
查找父元素: 在事件处理函数中,通过 $(this) 获取到当前点击的元素,然后使用 .closest() 方法找到包含 input 元素的最近的父元素。这样就可以在该父元素范围内查找 input 元素,从而获取到正确的 ID 值.
代码示例
以下是修改后的代码示例:
var data = [ {codigo: "1", Utente: "Teste", }, {codigo: "2", Utente: "Teste1", }, {codigo: "3", Utente: "Teste2",}, {codigo: "4", Utente: "Teste3", }, {codigo: "5", Utente: "Teste4", }, {codigo: "6", Utente: "Teste5", },];$(document).on('click', '.dad-inf', function(){var linha = ``;for (var i = 0; i < data.length; i++) {codigo = data[i].codigo;Utente = data[i].Utente;linha += ``; } $(".tesssste").html(linha);});$(document).on('click', '.histor-uten', function(e){ let parent = $(this); // First make sure it selects the element with the histor-uten class if(!parent.hasClass('histor-uten')){ parent = $(this).closest('.histor-uten'); } // Get the child input from the parent instead of the first one in the document var id_utt = $(parent.find("input[name='id_utt']")).val(); console.log(id_utt);});$(function() { $(".btn-show").click(function(e) { e.preventDefault(); el = $(this).data('element'); $(el).show(); $("section > div").not(el).hide(); });});
代码解释:
$(document).on(‘click’, ‘.histor-uten’, function(e){ … });: 这行代码使用了事件委托,将 click 事件监听器绑定到了 document 对象上,并指定了只有点击 class 为 .histor-uten 的元素时才会触发该事件。let parent = $(this);: 获取当前点击的元素,并赋值给 parent 变量。if(!parent.hasClass(‘histor-uten’)){parent = $(this).closest(‘.histor-uten’);}: 确保选择器选择的是具有 histor-uten 类的元素。var id_utt = $(parent.find(“input[name=’id_utt’]”)).val();: 这行代码首先使用 $(this).closest(‘.histor-uten’) 找到包含 input 元素的最近的父元素(class 为 .histor-uten 的 div),然后在该父元素范围内使用 find(“input[name=’id_utt’]”) 查找 input 元素,最后使用 .val() 方法获取其值。
HTML 结构
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js">Utentes
注意事项
确保 .histor-uten 类选择器能够唯一标识包含 input 元素的父元素。如果 HTML 结构发生变化,需要相应地调整 .closest() 方法的参数。
总结
通过使用事件委托和查找父元素的方式,可以有效地解决在使用 jQuery 动态生成 HTML 元素时,获取到错误 ID 值的问题。这种方法不仅适用于获取 input 元素的值,还可以用于获取其他任何需要根据点击元素动态获取的数据。理解和掌握这种技巧对于编写健壮的 jQuery 代码至关重要。
以上就是如何使用 jQuery 获取动态生成 div 中点击元素的正确 ID的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1597207.html
微信扫一扫
支付宝扫一扫