简体   繁体   中英

How to find the previous element height using jquery

I have a table which is defined like:

<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>

Then on button click I want to get the height of the previous control. So I wrote this code:

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

But the alert's are showing the values as undefined. How can I solve this?

Use:

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'));
}

Use real width() to get real width of an element instead of width defined in css ( .css('width') ). The same applies for height:

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

In fact there is no previous target of your buttons.

If you want the TD height, you should call .parent() instead.

And please, pay attention to your HTML !

EDIT: Fiddle updated: 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());
});

you can try: jsFiddle

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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