繁体   English   中英

如何使用jQuery查找先前的元素高度

[英]How to find the previous element height using jquery

我有一个表,其定义如下:

<table>
    <tr>
        <td>
            <label>First</label>
        </td>
        <td>
            <input type='text' style='widht:200px; height:100px;' />
        </td>
        <td>
            <button class='but'></button>
        </td>
    </tr>
    <tr>
        <td>
            <label>Second</label>
        </td>
        <td>
            <select style='widht:100px; height:150px;'>
                <option>one</one>
            </select>
        </td>
        <td>
            <button class='but'></button>
        </td>
    </tr>
    <tr>
        <td>
            <label></label>
        </td>
        <td>
            <input type='text' style='widht:200px; height:100px;' />
        </td>
        <td>
            <button class='but'></button>
        </td>
    </tr>
    <tr>
        <td>
            <label>Third</label>
        </td>
        <td>
            <textarea style='widht:500px; height:200px;'></textarea>
        </td>
        <td>
            <button class='but'></button>
        </td>
    </tr>
</table>

然后在按钮上单击我要获取上一个控件的高度。 所以我写了这段代码:

 $(".but").live('click',function(){
     alert($(this).prev().css('width'));
     alert($(this).prev().css('height'));
 });

但是警报将这些值显示为未定义。 我该如何解决?

采用:

var input = $(this).parent().prev().find("input");
if(input) { // You have a select, so this won't be found in all circumstances
    alert(input.css('width'));
    alert(input.css('height'));
}

使用real width()获取元素的实际宽度,而不是css( .css('width') )中定义.css('width') 高度也一样:

$(".but").live('click',function(){
    alert($(this).prev().width());
    alert($(this).prev().height());
});

实际上,您的按钮没有先前的目标。

如果需要TD高度,则应改为调用.parent()。

并且请注意您的HTML!

编辑:小提琴更新: http//jsfiddle.net/jVsRW/4/

$(".but").on('click', function() {
    // Of course display null for the first button that do not have a previous form element.
    alert($(this).closest('tr').prev().find('input, select, textarea').height());
});

您可以尝试: jsFiddle

$(".but").live('click',function(){
     alert($(this).closest("tr").find('input').css('width')); 
     // OR
     //alert($(this).closest("tr").find('select').css('width'));     
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM