You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过jQuery点击嵌套span元素获取pop-up-custom父元素的ID值?

如何用jQuery点击嵌套span时获取顶级父div的ID?

需求:点击嵌套在带有pop-up-custom类的顶级div内的<span>元素时,获取该顶级div的ID(示例中为ideation)。HTML由页面生成器自动生成,仅可修改顶级元素的ID和类。

给出的HTML结构

<div class="elementor-element pop-up-custom" id="ideation" data-widget_type="eael-lightbox.default">
    <div class="elementor-widget-container">
        <div data-lightbox-type="lightbox_type_custom_html" data-lightbox-type-url="" data-lightbox-trigger-pageload="1" data-lightbox-closebtn-color="#ffffff" class="eael-lightbox-wrapper" data-trigger="eael_lightbox_trigger_button" data-lightbox-id="lightbox_639c25cc43a03" data-type="inline" data-src="#eael-lightbox-window-639c25cc43a03" data-popup-layout="eael-lightbox-popup-standard" data-main-class="eael-lightbox-modal-popup-cf4e9a1" data-close_button="yes" data-esc_exit="yes" data-click_exit="yes" data-effect="animated " data-trigger-element=".eael-modal-popup-link-639c25cc43a03">
            <div class="eael-lightbox-btn">
                <span id="btn-eael-lightbox-639c25cc43a03" class="eael-modal-popup-button eael-modal-popup-link eael-modal-popup-link-639c25cc43a03 elementor-button elementor-size-md">Request</span>
            </div><!-- close .eael-lightbox-btn -->
        </div>
    </div>
</div>

当前代码的问题

你写的代码存在两个问题:

  1. 选择器.pop-up-custom > span是直接子元素选择器,但目标<span>并非pop-up-custom类div的直接子元素,中间嵌套了多层div,导致选择器无法匹配到目标元素。
  2. console.log(this.id)打印的是<span>自身的ID,不是顶级父div的ID。

正确的解决方案

方案1:直接绑定事件(静态元素适用)

jQuery(".pop-up-custom span").click(function() {
    // 向上查找最近的带有pop-up-custom类的父元素,获取其ID
    const parentDivId = jQuery(this).closest(".pop-up-custom").attr("id");
    console.log(parentDivId);
});

方案2:事件委托(动态生成元素适用)

如果页面中的<span>是动态生成的,使用事件委托确保事件能触发:

jQuery(document).on("click", ".pop-up-custom span", function() {
    const parentDivId = jQuery(this).closest(".pop-up-custom").attr("id");
    console.log(parentDivId);
});

核心逻辑说明

  • jQuery(this).closest(".pop-up-custom"):从当前点击的<span>元素开始,向上遍历DOM树,找到最近的带有pop-up-custom类的父元素(即目标顶级div)。
  • .attr("id"):获取该父元素的ID属性值。

内容的提问来源于stack exchange,提问作者Sanad Cal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:02:09