Javascript 如何使用jquery查找上一个元素的高度

Javascript 如何使用jquery查找上一个元素的高度,javascript,jquery,Javascript,Jquery,我有一个表,定义如下: <table> <tr> <td> <label>First</label> </td> <td> <input type='text' style='widht:200px; height:100px;' /> </td> <

我有一个表,定义如下:

<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>
但警报显示这些值未定义。如何解决这个问题?

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

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

事实上,您的按钮没有以前的目标

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

请注意你的HTML

编辑:小提琴更新:

使用:

您可以尝试:


您在html仅供参考中拼错了宽度<代码>$(this.prev().height();也许吧?@Naidu
嘿,对不起,错了。我改了,我看不见了。我仍然可以看到
和widht
@Naidu$('.but')是第一个元素,因此它没有任何以前的元素,因此您可以准确地说出您想要的元素的高度和宽度。如果您可以将类添加到以前的元素(如select、textarea、,输入等,因为容器中没有上一个元素。这取决于您需要获取的值,它是哪一个?
$(this)。prev().height()
正在显示
null
是的,当然,我想告诉您prev()和parent()之间的区别。在同一容器()中的按钮之前没有上一个元素,因此prev()不是元素。而不是parent(),这将是容器(,此处)。好的,但我不想要父级高度,我只想要元素高度。那两个人的身高不一样好吧我不明白。因此,您可以尝试:$(this).closest('tr').prev().find('input,select,textarea').height()。我已经更新了小提琴!
$(".but").live('click',function(){
    alert($(this).prev().width());
    alert($(this).prev().height());
});
$(".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());
});
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'));
}
$(".but").live('click',function(){
     alert($(this).closest("tr").find('input').css('width')); 
     // OR
     //alert($(this).closest("tr").find('select').css('width'));     
});