jQuery проверяет ширину ячейки и сравнивает с ее индексом

#javascript #jquery

#javascript #jquery

Вопрос:

Я создал довольно сложную часть jQuery, которая выполняет следующее:

1.) Найдите все <col> и <td> которые имеют класс flex

2.) Сохраняет ширину столбца из значения данных (это связано с тем, что ширина может быть переопределена, поэтому она хранится в атрибуте данных HTML5)

3.) Получает ширину a <td> (которая имеет класс flex) и использует ее для проверки ширины столбца. Если она больше, чем исходная, сделайте ее 100% или сделайте ее исходной шириной.

4.) Все это выполняется каждый раз, когда пользователь перемещает окно браузера

Проблема, с которой я сталкиваюсь, заключается в том, что, поскольку они представляют собой несколько столбцов flex или могут быть только одним, я использую метод поиска cols и tds, а затем также сохраняю их индексы, поскольку у них нет прямой связи между col и td, которые можно отслеживать с помощью CSS или JS.

Вот HTML:

 <div class="uiGrid flex">
    <table>
        <colgroup>
            <col class="flex" style="width:200px;" data-original="width:200px;" />
            <col style="width:100px;" data-original="width:100px;" />
            <col style="width:100px;" data-original="width:100px;" />
            <col class="flex" style="width:250px;" data-original="width:250px;" />
            <col style="width:100px;" data-original="width:100px;" />
        </colgroup>
        <thead>
            <tr>
                <th>Header</th>
                <th>Header</th>
                <th>Header</th>
                <th>Header</th>
                <th>Header</th>
            </tr>
        </thead>
        <tbody>
            <td class="flex">Cell</td>
            <td>Cell</td>
            <td>Cell</td>
            <td class="flex">Cell</td>
            <td>Cell</td>
        </tbody>
    </table>
</div>
 

и вот JS, который у меня есть:

 var columnWidth,columnIndex,cellWidth,cellIndex,columnData,thiscolumnWidth;

uiGrid = {

    getOriginal: function () {

        /* Check if the grid is flexible */
        if ($('.uiGrid.flex').length > 0) {

            columnData = new Array();
            // For each flex column
            $('.uiGrid table col.flex').each(function (i) {

                // Get its original width and strip out extra bits of css
                columnWidth = $(this).data('original');
                columnWidth = columnWidth.replace('width:', '');
                columnWidth = columnWidth.replace('px', '');
                columnWidth = columnWidth.replace(';', '');

                // Get its index
                columnIndex = $(this).index();

                // Creates an array of columnData with an array of data
                columnData[i] = new Array(columnWidth, columnIndex);
            });
        }
    },

checkWidth: function () {

        cellIndex = new Array();

        cellWidth = new Array();

        // For each flex cell in the first row
        $('.uiGrid table tr:first-child td.flex').each(function (i) {

            // Get its current width
            cellWidth[i] = $(this).width();

            cellIndex[i] = $(this).index();

            // For each columnData array
            $(columnData).each(function () {
                // If this columnData array second value matches the cellIndex
                //console.log('this'   this[1]);
                //console.log('cell'   cellIndex[i]);
                if (this[1] == cellIndex[i]) {
                    // thiscolumnWidth takes this columnData array first value as its value
                    thiscolumnWidth = this[0];
                }
            });

            // For each cellWidth array
            $(cellWidth).each(function () {
                console.log(this);
                                // If the cellWidth is less than the passed down column width
            if (this < thiscolumnWidth) {
                // Apply the original width to a col with an index that matches the cell index  
                $('col.flex:eq('   cellIndex[i]   ')').css('width', thiscolumnWidth);
                $('td.flex:eq('   cellIndex[i]   ')').css('background-color', '#ff0000');
            }
            else {
                // Apply a flexible width to a col with an index that matches the cell index
                $('col.flex:eq('   cellIndex[i]   ')').css('width', '100%');
                $('td.flex:eq('   cellIndex[i]   ')').css('background-color', '#ff0000');
            }

            });

        });
    }
};

$(document).ready(function () {
    uiGrid.getOriginal();
    uiGrid.checkWidth();
    $(window).resize(function () {
        uiGrid.checkWidth();
    });
});
 

Итак, проблема в том, что она не работает должным образом! Первый TD с flex работает, но не второй? Так что, как будто где-то путается с нумерацией.

Ошибок нет (ПРИМЕЧАНИЕ: у меня это работало в предыдущем примере, но с тех пор я изменил его для работы с классами flex, поэтому я знаю, что теория определенно работает)

Может ли кто-нибудь увидеть какие-либо явные проблемы или иметь возможность протестировать их и посмотреть, смогут ли они это выяснить.

РЕДАКТИРОВАТЬ: Довольно интересно, что я добавил две новые строки, чтобы добавить красный фон к относительным TDS к столбцам, которые должны меняться, и они далеки! НО он окрашивает две ячейки, но как в разных столбцах, так и в разных строках, так что проблема, безусловно, в подсчете!

EDIT2: я создал для этого скрипку http://jsfiddle.net/mFxCy /

Комментарии:

1. Можете ли вы создать jsfiddle для этого?

2. Вы пытаетесь скопировать свойство CSS min-width ?