Скрыть / показать строку таблицы с учетом индекса строки и идентификатора таблицы

0

В настоящее время у меня есть этот код для удаления строки таблицы:

var remove = document.getElementById(dataID); (this is the id of an object in the row I wish to hide)
    if(remove!=null){
        var v = remove.parentNode.parentNode.rowIndex;
        document.getElementById(tid).deleteRow(v); (tid is the table id, not the row id)
    }

Однако, вместо удаления, я просто хотел бы скрыть это. Какой хороший способ сделать это?

Кроме того, в будущем мне захочется "показать" его по запросу пользователя, так как я могу проверить, скрыта ли она? Значение if (remove! = Null) проверяется, если строка уже удалена, поэтому мне нужно что-то подобное.

Спасибо за ваше время.

Теги:

3 ответа

2
Лучший ответ

document.getElementById(tid).children[dataID].style.display = 'none';

Возможно, вам понадобится -1 в dataID

И block чтобы показать его снова (или inline или что бы он ни был, для block div).

JQuery:

$('#'+tid+':nth-child('+dataID+')').hide();

  • 0
    Извините, я не верю, что был достаточно ясен в своем вопросе. 'tid' - это не идентификатор строки, которую я хочу скрыть, это идентификатор таблицы. У меня под рукой есть идентификатор таблицы и индекс строки, которую я хочу скрыть.
  • 0
    Хорошо, как насчет этого?
Показать ещё 4 комментария
1

Поскольку вы попросили решение jQuery... как насчет

var $remove = $('#' + dataID);

if ($remove) {
    $remove.closest('tr').closest().hide();
}

?

  • 1
    Пожалуйста, используйте closest('tr') вместо навигации по (потенциально произвольному) происхождению элемента.
  • 0
    Правда, отредактировал мой ответ, чтобы отразить это.
1

Мой собственный подход, в простом JavaScript:

function toggleRow(settings) {
    // if there no settings, we can do nothing, so return false:
    if (!settings) {
        return false;
    }
    // otherwise, if we have an origin,
    // and that origin has a nodeType of 1 (so is an element-node):
    else if (settings.origin && settings.origin.nodeType) {
        // moving up through the ancestors of the origin, until
        // we find a 'tr' element-node:
        while (settings.origin.tagName.toLowerCase() !== 'tr') {
            settings.origin = settings.origin.parentNode;
    }
        // if that tr element-node is hidden, we show it,
        // otherwise we hide it:
        settings.origin.style.display = settings.origin.style.display == 'none' ? 'table-row' : 'none';
    }
    // a simple test to see if we have an array, in the settings.arrayOf object,
    // and that we have a relevant table to act upon:
    else if ('join' in settings.arrayOf && settings.table) {
        // iterate through that array:
        for (var i = 0, len = settings.arrayOf.length; i < len; i++) {
            // toggle the rows, of the indices supplied:
            toggleRow({
                origin: table.getElementsByTagName('tr')[parseInt(settings.arrayOf[i], 10)]
            });
        }
    }
}

// you need an up-to-date browser (you could use 'document.getElementById()',
// but I'm also using 'addEventListener()', so it makes little difference:
var table = document.querySelector('#demo'),
    button = document.querySelector('#toggle');
// binding a click event-handler to the 'table' element-node:
table.addEventListener('click', function (e) {
// caching the e.target node:
var t = e.target;
    // making sure the element is a button, and has the class 'removeRow':
    if (t.tagName.toLowerCase() === 'button' && t.classList.contains('removeRow')) {
        // calling the function, setting the 'origin' property of the object:
        toggleRow({
            origin: t
        });
    }
});

// binding click-handler to the button:
button.addEventListener('click', function () {
    // calling the function, setting the 'arrayOf' and 'table' properties:
    toggleRow({
        'arrayOf': document.querySelector('#input').value.split(/\s+/) || false,
            'table': table
    });
});

Демо-версия JS Fiddle.

Рекомендации:

Ещё вопросы

Сообщество Overcoder
Наверх
Меню