gpt4 book ai didi

javascript - 在 mouseover/mouseout 事件中使用 $this 关键字声明变量

转载 作者:行者123 更新时间:2023-12-03 01:18:36 25 4
gpt4 key购买 nike

我可以正常执行以下操作。但我想知道声明变量的最佳方式是什么,使用 $this,仅使用一次而不是重复两次。

$('table tr td').mouseover(function(){

var index = $(this).index() + 1,
allColumn = $('table tr td:nth-child('+ index +')');

allColumn.addClass('highlight');

});

$('table.data tr td').mouseout(function(){

var index = $(this).index() + 1,
allColumn = $('table tr td:nth-child('+ index +')');

allColumn.removeClass('highlight');

});

最佳答案

其中一种方法是使用单个 on 方法附加所有事件,并声明变量并检查事件类型。然后添加或删除类

$('table.data tr td').on('mouseover mouseout', function(e) {

index = $(this).index() + 1,
allColumn = $('table tr td:nth-child(' + index + ')');
if (e.type === 'mouseover') { // type of event
allColumn.addClass('highlight');

} else if (e.type === 'mouseout') { // type of event
allColumn.removeClass('highlight');
}
})
.highlight {
background: red;
color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1px solid black" class="data">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>

关于javascript - 在 mouseover/mouseout 事件中使用 $this 关键字声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51869090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com