为什么在我的jQuery中使用下一个'div'不起作用?

atc*_*way 1 asp.net jquery

我有以下jQuery 确实找到了ASP.NET服务器控件(通过在块中放置一个alert()进行测试),但它没有使用.next()在DOM中的下一个DIV上设置高度.但是,如果我使用直接JS做同样的事情,直接通过ID调用DIV它工作正常.

我想要做的是不使用DIV的硬编码ID以防它改变,而是走DOM以动态地获取元素并设置高度.

所以第一:我试图操纵的HTML源代码:

<div id="WebViewer" style="height:100%;width:100%;margin-right: 0px">
   <input name="WebViewerReportReceipt" type="hidden"/>
   <input name="WebViewerViewerType" type="hidden"/>
   <DIV id="WebViewer_controlDiv">
    <iframe src="295769102_1619997395_16141400_2120403583/CacheItem" style="width:100%;height:100%;"></iframe>
   </DIV>
</div>
Run Code Online (Sandbox Code Playgroud)

接下来我认为应该工作的非工作jQuery :

//Using the 'DIV' that is created by the viewer (at runtime), resize it dynamically to fit the window
    var myHeight = $(window).height();
    if ($('#<%=WebViewer.ClientID %>') != null) {                
          $('#<%=WebViewer.ClientID %>').next('div').height(myHeight - 10);
    }
Run Code Online (Sandbox Code Playgroud)

最后一点是,JS 的工作,但我宁愿不被硬编码ID访问DIV和使用jQuery来代替:

var myHeight = $(window).height();
//Using the 'DIV' that is created by the viewer (at runtime), resize it dynamically to fit the window
if (document.getElementById('WebViewer_controlDiv') != null) {
    document.getElementById('WebViewer_controlDiv').style.height = myHeight - 10;
}
Run Code Online (Sandbox Code Playgroud)

关于为什么在jQuery中使用DOM来获取"下一个"div并设置其高度的任何想法都不起作用?

谢谢!

lon*_*day 7

就HTML而言,它可能是"下一个",但就DOM而言,它不是"下一个".相反,它是一个孩子.

你可能想要这样的东西:

$(element).find('div:first');
Run Code Online (Sandbox Code Playgroud)

但请注意,您的代码存在一些问题.例如,这将始终通过:

if ($('#<%=WebViewer.ClientID %>') != null) {
Run Code Online (Sandbox Code Playgroud)

您需要检查length选择的属性,因为即使是空的jQuery选择也会计算为布尔值true.