2016-03-15 74 views
0

我有一个图像,当点击时需要抓住图像的父div之前的div的ID。 prev()方法返回一个对象,但ID始终未定义。以下是我的:为什么JQuery的Prev()对象不给我一个ID?

function getParentDiv(thisitem,action) { 
    while (thisitem && (thisitem.tagName != "DIV" || !thisitem.id)) 
     thisitem = thisitem.parentNode; 
    if (thisitem) checkForSibling(thisitem); 
} 

function checkForSibling(thisitem) { 
    var thisDivId = thisitem.id; 
    var sibling = $("#"+thisDivId).prev("div").attr("id"); 
} 

为什么兄弟姐妹总是未定义?

编辑:

我,我们在工作中有系统的限制范围内工作,所以不得不从外景主持人的JavaScript之外的应用程序和通话功能形成有(不知道是否是有区别)。下面是如何创建一个包含调用上述功能的图像一个新的div:

function createNewTextElementDiv(divName, placeHolder, elType, elSize, elSpacing) { 
document.getElementById(placeHolder).innerHTML += "<div id='"+divName+"'><table width='465'><tr><td width='170px' valign='top'><span class='smallgreybold'>Text Element</span>&nbsp;<span class='mediumorangebold' style='font-size: 20;'>+</span></td><td width='295px' align='right' valign='center'><img src='/html/106789/arrow-up.png' style='border:0; height:20px; width:20px; background-color:transparent' onclick='getParentDiv(this,\"Up\")'></img>&nbsp;&nbsp;<img src='/html/106789/arrow-down.png' style='border:0; height:20px; width:20px; background-color:transparent' onclick='getParentDiv(this,\"Down\");'></img>&nbsp;&nbsp;<img src='/html/106789/remove-button.png' style='border:0; height:20px; width:20px; background-color:transparent' onclick='getParentDiv(this,\"Remove\");'></img></td></tr></table><span class='smallgrey'>Text Type: </span><span class='smallgreybold'>"+elType+"</span><span class='smallgrey'>&nbsp;&nbsp;Text Size: </span><span class='smallgreybold'>"+elSize+"</span><span class='smallgrey'>&nbsp;&nbsp;Spacing: </span><span class='smallgreybold'>"+elSpacing+"</span><br><hr></div>"; } 

有一些静态的div中的应用,以及那些我创建的飞行,所以我需要的Id父母之前的div。提前致谢。

+3

安置自己的HTML代码和你打电话给你的JS代码,请了道路。 –

+0

你在混合使用jQuery和纯JS,所以在这里弄清楚什么是错误有点困难。我建议一个jQuery解决方案:'$(thisitem).closest(“div”)。prev(“div”)。attr(“id”)'。希望可以帮助 –

+0

我试图避免使用jQuery tbh,但遇到了一堵砖墙,于是扔了毛巾,转向jQuery! – user2634236

回答

1

请使用这样的:

function checkForSibling(thisitem) { 
    var thisDivId = thisitem.id; 
    var sibling = $("#"+thisDivId).parent().prev("div").attr("id"); 
} 

需要添加.parent()

+0

这给我一个不明物体恐怕 – user2634236

+0

请警惕(thisDivId);并检查它是否给你正确的ID。 –

+0

这是给我预期的ID – user2634236

相关问题