Как jQuery может найти номер строки кнопки, нажатой в динамически генерируемой таблице? - PullRequest
1 голос
/ 27 октября 2009

У меня есть таблица, которая выглядит так:

<table>
    <thead>
        <!-- random table headings -->
    </thead>
    <tbody>
        <tr class="readonly">
            <td><input type="text" readonly="readonly" name="bookings[start][]" class="date" value="start"/></td>
            <td><input type="text" readonly="readonly" name="bookings[end][]" class="date" value="end"/></td>
            <td><input type="text" readonly="readonly" name="bookings[comment][]" value="comment"/></td>
            <td>
                <button type="button" class="control edit" title="Edit this row">Edit</button>
                <button type="button" class="control delete" title="Delete this row">&times;</button>
                <!-- delete button needs to know the posistion of the row
                     in the table so that it can remove its array entry -->
            </td>
        </tr>
        <!-- ^ inserted as required by the button in tfoot -->
    </tbody>
    <tfoot>
        <tr>
            <td><input type="text" id="startinput" class="date" value=""/></td>
            <td><input type="text" id="endinput" class="date" value=""/></td>
            <td><input type="text" id="commentinput" value=""/></td>
            <td><button type="button" class="control add" title="Add to the table">+</button></td>
        </tr>
    </tfoot>
</table>

Чтобы правильно реализовать кнопку удаления, необходимо рассчитать индекс строки, в которой находится кнопка. Как я могу сделать это в JQuery? Вот текущий код:

$("button.delete").live("click",function()
{
    var row = $(this).parent().parent();
    row.addClass("deleting");
    if(confirm("delete this row?"))
    {
        var row idx = /*???*/;
        datelist.bookings.splice(idx,1);
        row.remove();
    }
    else
    {
        row.removeClass("deleting");
    }
});

Спасибо.

1 Ответ

5 голосов
/ 27 октября 2009

Это даст вам нулевой индекс строки в теле.

var row_idx = row.prevAll().length;

Просто к вашему сведению, технически tfoot должен появляться перед tbody (для корректного HTML). Кроме того, технически возможно иметь несколько элементов tbody.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...