我正在尝试获取事件目标父父对象的 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-pencil
的parent().parent()
是.grid-stack-item
元素,没有编号
。我假设您正在尝试以 #chart
元素为目标,因为它是您的 HTML 示例中唯一具有 id
的元素。如果是这种情况,您的代码将失败,因为该元素是父元素的同级。在这种情况下,您可以使用 prev()
来获取它。试试这个:
var chartID = $(this).parent().prev().prop('id');
或者:
var chartID = $(this).closest('.overlayed').prev().prop('id');
关于javascript - 无法获取父 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869119/