讲师中心 微信公众号
AI工具推荐 视频效率加速

如何根据点击的 Div 获取正确的 ID

大晨君_9764

大晨君_9764

发布时间:2025-11-18 11:58:00

|

674人浏览过

|

来源于php中文网

原创

如何根据点击的 div 获取正确的 id

本文旨在解决在使用 jQuery 动态生成内容时,点击事件无法获取正确 ID 的问题。通过事件委托和 DOM元素查找,我们将演示如何确保点击事件能够准确地获取到与点击元素相关联的 ID 值,从而避免获取到错误的 ID。

在使用 jQuery 进行动态内容生成时,经常会遇到点击事件无法正确获取目标元素 ID 的情况。这通常是因为事件绑定发生在元素生成之前,或者选择器选取了错误的元素。本教程将通过一个实际案例,详细讲解如何利用事件委托和正确的 DOM 元素查找方法,来解决这个问题。

问题分析

在提供的代码中,点击 .histor-uten 元素时,总是获取到第一个 input[name='id_utt'] 的值,而不是与当前点击元素关联的 input 元素的值。这是因为选择器 $("input[name='id_utt']").val() 总是返回页面上第一个匹配的元素的值,而没有考虑到上下文关系。

解决方案:事件委托和 DOM 元素查找

解决此问题的关键在于使用事件委托,并将查找范围限定在当前点击的元素内部。

Wechat Article Html
Wechat Article Html

将 Markdown 文章转换为微信公众号兼容的纯 HTML 格式。当用户要求"转成微信格式"、"生成公众号文章 HTML"、"排版到微信草稿箱"、"微信粘贴格式"时触发。输出带内联样式的纯 HTML,微信编辑器可直接渲染,无需额外适配。支持标题、段落、列表、粗体、行内代码、表格、引用块、代码块、配图的完整转换。

下载
  1. 事件委托: 将事件监听器绑定到父元素(例如 .tesssste),利用事件冒泡机制,当子元素 .histor-uten 被点击时,事件会冒泡到父元素,从而触发事件监听器。
  2. DOM 元素查找: 在事件处理函数中,使用 $(this) 获取当前点击的元素,然后使用 find() 方法在该元素内部查找目标 input 元素。

以下是修改后的代码:

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 += `<div class="col-md-6 col-xl-3">
            <a href="#" class="dropdown-item btn btn-warning histor-uten">
              <div class="profile-photo-div" id="profile-photo-div">
                <div class="profile-buttons-div">
                  <div class="profile-img-input" id="profile-img-input">
                    <label class="butttton" id="change-photo-label" for="change-photo">#${Utente}</label>
                    <input type="hidden" name="id_utt" value="${codigo}">
                  </div>
                </div>
               </div>
              </a>
            </div>`;
    }

    $(".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) { ... });: 使用事件委托,将点击事件绑定到 document 上,监听 .histor-uten 元素的点击事件。
  • let parent = $(this);: 获取当前点击的 .histor-uten 元素。
  • if (!parent.hasClass('histor-uten')) { parent = $(this).closest('.histor-uten'); }: 确保选择器选中了 .histor-uten 元素。
  • var id_utt = $(parent.find("input[name='id_utt']")).val();: 在当前点击的 .histor-uten 元素内部查找 input[name='id_utt'] 元素,并获取其值。

完整 HTML 代码

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.min.js"></script>

<a href="s105" data-element="#minhaDiv105" class="btn-show dad-inf">Utentes</a>

<section id="s105">
    <div id="minhaDiv105">
        <div class="row tesssste">
        </div>
    </div>
</section>

<script>
    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 += `<div class="col-md-6 col-xl-3">
            <a href="#" class="dropdown-item btn btn-warning histor-uten">
              <div class="profile-photo-div" id="profile-photo-div">
                <div class="profile-buttons-div">
                  <div class="profile-img-input" id="profile-img-input">
                    <label class="butttton" id="change-photo-label" for="change-photo">#${Utente}</label>
                    <input type="hidden" name="id_utt" value="${codigo}">
                  </div>
                </div>
               </div>
              </a>
            </div>`;
        }

        $(".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();
        });
    });
</script>

总结

通过使用事件委托和正确的 DOM 元素查找方法,我们可以确保在动态生成的内容中,点击事件能够准确地获取到与点击元素相关联的 ID 值。 这种方法不仅解决了当前问题,也为处理类似的动态内容交互提供了通用的解决方案。 在实际开发中,应根据具体情况灵活运用这些技巧,提高代码的健壮性和可维护性。

热门AI工具

更多
小橡皮AI

一款AI工具,主要用于小橡皮一键去AI味,将机器味重的内容改得更有活人感,防止因为 AI 内容被平台打上 AI 标签,以及限流,适合需要提升相关任务效率的用户。

Atoms
Atoms Hot

Atoms是一款AI智能体工具,第一支自动构建真实业务的 AI 团队。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

讯飞智作

讯飞智作是一款AI视频创作工具,AI文本配音工具,数字人课程、营销视频制作。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

PixTV
PixTV Hot

PixTV是一款面向AIGC内容创作的AI视频生成工具。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

AionClaw
AionClaw Hot

AionClaw是一款面向办公、创作和编程任务的AI桌面智能体。

相关专题

更多
jquery插件有哪些
jquery插件有哪些

jquery插件有jQuery UI、jQuery Validate、jQuery DataTables、jQuery Slick、jQuery LazyLoad、jQuery Countdown、jQuery Lightbox、jQuery FullCalendar、jQuery Chosen和jQuery EasyUI等。本专题为大家提供jquery插件相关的文章、下载、课程内容,供大家免费下载体验。

601

2023.09.12

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

1156

2023.10.13

jquery删除元素的方法
jquery删除元素的方法

jquery可以通过.remove() 方法、 .detach() 方法、.empty() 方法、.unwrap() 方法、.replaceWith() 方法、.html('') 方法和.hide() 方法来删除元素。更多关于jquery相关的问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

2242

2023.11.10

jQuery hover()方法的使用
jQuery hover()方法的使用

hover()是jQuery中一个常用的方法,它用于绑定两个事件处理函数,这两个函数将在鼠标指针进入和离开匹配的元素时执行。想了解更多hover()的相关内容,可以阅读本专题下面的文章。

2148

2023.12.04

jquery实现分页方法
jquery实现分页方法

在jQuery中实现分页可以使用插件或者自定义实现。想了解更多jquery分页的相关内容,可以阅读本专题下面的文章。

493

2023.12.06

jquery中隐藏元素是什么
jquery中隐藏元素是什么

jquery中隐藏元素是非常重要的一个概念,在使用jquery隐藏元素之前,需要先了解css样式中关于元素隐藏的属性,比如display、visibility、opacity等属性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

337

2024.02.23

jquery中什么是高亮显示
jquery中什么是高亮显示

jquery中高亮显示是指对页面搜索关键词时进行高亮显示,其实现办法:1、先获取要高亮显示的行,获取搜索的内容,再遍历整行内容,最后添加高亮颜色;2、使用“jquery highlight”高亮插件。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

766

2024.02.23

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

289

2026.01.13

Gradle插件开发入门教程
Gradle插件开发入门教程

本专题介绍Gradle插件开发的基本流程,涵盖插件类编写、自定义任务注册、扩展参数设计和插件应用方法,帮助你理解插件如何组织构建逻辑,减少多个项目之间的重复配置。

80

2026.10.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 1.5万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 6.1万人学习

CSS教程
CSS教程

共754课时 | 98.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn