javascript - 无法获取父 ID

标签 javascript jquery html

我正在尝试获取事件目标父父对象的 ID,但它返回时未定义,但我知道这个 ID 确实存在,因为我已经使用 firebug 来确认这一点。

这是我的 html 标记:

<div class="grid-stack-item ui-draggable ui-resizable ui-resizable-autohide" data-gs-x="0" data-gs-y="0" data-gs-width="4" data-gs-height="4">
        <div class="grid-stack-item-content ui-draggable-handle" id="chart"></div>
        <div class="overlayed" data-render="" data-chartType="" data-devID="" data-metricType="" data-refresh="30000" data-title="" data-subtitle=""
                    data-yAxis="" data-tooltip="" data-lineWidth="0.5" data-timeWindow="10">
            <span class="glyphicon glyphicon-pencil panel-icons chart-edit" style="padding-right: 10px"></span>
            <span class="glyphicon glyphicon-zoom-in panel-icons"></span>
            <span class="glyphicon glyphicon-trash panel-icons"></span>
        </div>
    </div>

这是我尝试获取 id 的 javascript/jquery

$('.overlayed').on('click', '.glyphicon-pencil', function (e) {
    e.preventDefault();
    e.stopPropagation();
    alert("what is going on!");
    //hold the overlayed element for later use
    var overlayedData = $(this);
    var chartID = $(this).parent().parent().attr('id');

    $('#editWidgetModal').modal('toggle');
}

最佳答案

.glyphicon-pencilparent().parent().grid-stack-item元素,没有编号。我假设您正在尝试以 #chart 元素为目标,因为它是您的 HTML 示例中唯一具有 id 的元素。如果是这种情况,您的代码将失败,因为该元素是父元素的同级。在这种情况下,您可以使用 prev() 来获取它。试试这个:

var chartID = $(this).parent().prev().prop('id');

或者:

var chartID = $(this).closest('.overlayed').prev().prop('id');

Working example

关于javascript - 无法获取父 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869119/

相关文章:

javascript - 哪个是在 vue js 中将数据组件传递给组件的最佳方式

jquery - 无法使 div 箭头指向右上角的菜单

javascript - 如何在对象文字中使用 `this`?

html - Django模板如何重复使用模板html文件两次

html - 我如何强制缩小的 svg 图像彼此相邻排列而不是换行/被推到下一行?

javascript - 如果广告使用 document.write,如何在页面最后或异步加载广告代码?

javascript - JQuery UI Datepicker 改变一天的样式

javascript - 查看具有为所有 div 调用函数的同一类的多个 div?

jQuery 自动完成 : How to show an animated gif loading image

html - 禁用 Bootstrap 中的链接