登录
首页 >  文章 >  前端

如何正确获取Div的ID值

时间:2025-12-10 10:42:33 273浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《点击Div获取正确ID的方法》,聊聊,我们一起来看看吧!

如何在点击的Div中获取正确的ID

本文旨在解决动态生成的HTML元素中,点击事件发生时,如何准确获取与该元素关联的ID值的问题。通过事件委托和DOM遍历,我们将提供一种可靠的方法,确保在复杂的动态环境中,始终能获取到正确的ID,避免因选择器错误而导致的数据获取错误。

在动态生成的HTML结构中,经常会遇到点击事件需要获取特定ID的情况。如果直接使用jQuery选择器,可能会因为DOM结构的变化或选择器范围过大而导致获取到错误的ID。本文将介绍如何使用事件委托和DOM遍历,准确地获取与点击元素相关的ID。

问题分析

原始代码的问题在于,点击.histor-uten元素时,$("input[name='id_utt']").val() 总是返回第一个匹配的input元素的value,而不是当前点击的.histor-uten元素内部的input元素的value。这是因为选择器$("input[name='id_utt']")会选择页面上所有name属性为id_utt的input元素,并返回第一个匹配项的值。

解决方案:事件委托与DOM遍历

解决此问题的关键在于:

  1. 事件委托: 将事件监听器绑定到父元素,利用事件冒泡机制,监听子元素的点击事件。
  2. DOM遍历: 在事件处理函数中,通过DOM遍历,找到当前点击元素内部的input元素,并获取其value。

以下是修改后的代码:

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>
                    &lt;input type=&quot;hidden&quot; name=&quot;id_utt&quot; value=&quot;${codigo}&quot;&gt;
                  </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元素的点击事件。 这样做的好处是,即使.histor-uten元素是动态生成的,也能正确绑定事件。
  • let parent = $(this);: 获取当前点击的.histor-uten元素。$(this)指向触发事件的DOM元素。
  • if (!parent.hasClass('histor-uten')) { parent = $(this).closest('.histor-uten'); }: 确保 parent 变量指向 .histor-uten 元素。 如果点击事件发生在 .histor-uten 元素的子元素上,则使用 .closest() 方法找到最近的父元素 .histor-uten。
  • var id_utt = $(parent.find("input[name='id_utt']")).val();: 使用parent.find("input[name='id_utt']")在当前点击的.histor-uten元素内部查找name属性为id_utt的input元素,并获取其value。

完整示例

<!DOCTYPE html>
<html>

<head>
    <title>Get ID Example</title>
    <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>
</head>

<body>

    <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>
                    &lt;input type=&quot;hidden&quot; name=&quot;id_utt&quot; value=&quot;${codigo}&quot;&gt;
                  </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>

</body>

</html>

注意事项

  • 确保事件委托的父元素存在于DOM中。
  • DOM遍历时,选择器要足够精确,避免选择到错误的元素。
  • 如果HTML结构发生变化,需要相应地调整DOM遍历的代码。

总结

通过使用事件委托和DOM遍历,可以准确地获取动态生成的HTML元素中与点击事件相关的ID。这种方法避免了全局选择器可能导致的问题,提高了代码的健壮性和可维护性。在复杂的Web应用中,掌握这些技巧至关重要。

终于介绍完啦!小伙伴们,这篇关于《如何正确获取Div的ID值》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>