从它的父元素数组列表中获取元素的数组索引

时间:2014-09-09 08:43:18

标签: javascript jquery arrays dom hover

我的情况是我有一张桌子,每张桌子中的细胞都是一系列的div。将鼠标悬停在表格中的一个div上时,我希望相应的标签更改其背景颜色。标签有一个独立的div类。

所以,我在想的是,将要悬停的div和标签都在同一个表行(tr)元素中。包含标签div的单元格(td)与其他单元格具有单独的类别。标签div与div的关系是1:1。

因此,ParentCell.DivImHoveringOver [arrayIndex] = LabelCell.LabelDivIWantToChange [arrayIndex]。我的观点是,父元素子列表中两个元素的数组索引是相同的,所以我可以用它来悬停在另一个div上时更改标签div。

我该怎么做?

我想它会是这样的:

$('.table-day-detail-container').hover(
function() { //On hover entry
    //Get array index of this element from it's parents children array list.
    //Use that index to change background colour of another elements child node with that same array index
},
function() {//On hover exit
    //Revert background colour 
 }
);

表格单元格中的元素我将悬停在::

<td class="table-day">
    <div class="table-day-detail-container">Test1</div>
    <div class="table-day-detail-container">Test2</div>
</td>

表格单元格中的元素是悬停在相应元素上时要修改的标签

<td class="table-day-label">
    <div class="table-day-labels">Label1</div>
    <div class="table-day-labels">Label2</div>
</td>

1 个答案:

答案 0 :(得分:0)

您可以使用.index()之类的

$('.table-day-detail-container').hover(function () {
    var $this = $(this),
        index = $this.index();
    $this.parent().next().children('.table-day-labels').eq(index).css('background', 'red');
}, function () {
    var $this = $(this),
        index = $this.index();
    $this.parent().next().children('.table-day-labels').eq(index).css('background', '');
});

演示:Fiddle

相关问题