不能得到父母的身份

时间:2015-09-30 14:46:23

标签: javascript jquery html5

我试图获取事件目标父母的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>

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

$('.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');
}

1 个答案:

答案 0 :(得分:3)

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

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

或者:

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

Working example

相关问题