gpt4 book ai didi

javascript - 在表格单元格上设置 onmouseover

转载 作者:行者123 更新时间:2023-12-03 07:39:28 33 4
gpt4 key购买 nike

在第二个(右/bing)表条目中,我理解为什么从图像悬停到“bing”字符串可能会导致 bingfn()被解雇。

但是第一个(左/谷歌)表有 onmouseover<td> ,因此我预计从图像悬停到文本并返回不会导致计数器增加。为什么计数器会增加?拥有一个<a>有什么问题吗?围绕项目组合(在本例中为 <img><br /> 和一些文本)?

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<h3>On Mouse Over in tables</h3>
<table>
<tr>
<td onmouseover="googlefn()">
<a href="http://google.com/">
<img width="100" src="google.jpg">
<br />
Google
</a>
</td>
<td>
<p onmouseover="bingfn()">
<a href="http://bing.com/">
<img width="100" src="bing.jpg"><br />
Bing</a></p>
</td>
</tr>
<tr>
<td id="gcountarea">G.count</td>
<td id="bcountarea">B.count</td>
</tr>
</table>

<script>
var gcount = 0;
var bcount = 0;

function googlefn() {
document.getElementById("gcountarea").innerHTML = gcount+=1;
}

function bingfn() {
document.getElementById("bcountarea").innerHTML = bcount+=1;
}
</script>

</body>
</html>

最佳答案

我想我会将其分解为函数并将状态封装到一个类中。例如:

function Counter(identifier) {
this.count = 0;
this.identifier = identifier;
this.el = document.querySelector('.counter.' + identifier);
this.hoverEl = document.querySelector('[data-counter=' + identifier + ']');
}
Counter.prototype.includesElement = function(el) {
return this.hoverEl.contains(el);
};
Counter.prototype.mark = function() {
this.count++;
return this;
};
Counter.prototype.display = function() {
this.el.innerHTML = '' + this.count;
return this;
};

var counters = [
new Counter('google'),
new Counter('bing')
];

document.addEventListener('mouseover', function (evt) {
counters.forEach(function (counter) {
if (counter.includesElement(evt.target)) {
counter.mark().display();
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<h3>On Mouse Over in tables</h3>
<table>
<tr>
<td data-counter="google">
<a href="http://google.com/">
<img width="100" src="google.jpg">
<br />
Google
</a>
</td>
<td data-counter="bing">
<p>
<a href="http://bing.com/">
<img width="100" src="bing.jpg"><br />
Bing</a></p>
</td>
</tr>
<tr>
<td class="counter google">G.count</td>
<td class="counter bing">B.count</td>
</tr>
</table>
</body>
</html>

关于javascript - 在表格单元格上设置 onmouseover,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35469110/

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