在表行中定位类

时间:2014-02-28 16:33:16

标签: javascript html-table

代码:

var table = document.getElementById('some-table');
var row = table.rows;

alert(row.length); // Returns number of rows

// Function to hide class on specific row when some action is performed
function someFunc(i) {
    var elementToTarget = row[i].getElementsByClassName('some-class');
    var otherElementToTarget = row[i].getElementsByClassName('some-other-class');

    elementToTarget.style.display="none"; // Returns "elementToTarget.style
                                          //          is undefined"
    otherElementToTarget.style.display="inline"; // Returns undefined
}

基本表格布局:

<table>
    <tr>
        <td>
            <div class="some-class"></div>
            <div class="some-other-class"></div>
        </td>
    </tr>
</table>

我想做什么:当用户触发someFunc()时,它会隐藏某个类并显示其他类。但它只为某一特定行隐藏了一些类。不是所有的行。

我的问题:它告诉我该行中的元素未定义,我无法对它们执行任何操作。我很可能不正确地针对这些课程。

希望我已经足够清楚了。如果您需要更多说明,请告诉我。

编辑:行中可能并不总是有“某些其他类”。这就是为什么我不能只针对其中一个div。我需要知道他们的行。

1 个答案:

答案 0 :(得分:1)

我会引用你的getElementsByClassName函数的API。 https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName

另外,请注意名称 - 元素* s * 。它返回一个列表。你的功能应该相应地对待它。所以,例如:

var elementToTarget = row[i].getElementsByClassName('some-class')[0];
var otherElementToTarget = row[i].getElementsByClassName('some-other-class')[0];

看看这个小提琴:http://jsfiddle.net/YD78S/