【发布时间】:2019-05-03 02:52:42
【问题描述】:
我是这里的菜鸟,感谢一些关于我正在尝试解决的问题的建议。我意识到在不使用对象构造函数的情况下可能有更好的方法来做到这一点,但我正在努力更好地理解对象。我的问题是是否有类似 this.function 的东西引用了所有其他没有调用我的函数的对象。这是我想要完成的任务:
<!doctype HTML>
<html>
<head>
<title>Test</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
}
a:visited {
text-decoration: none;
color: black;
}
</style>
</head>
<body>
<ul>
<li><a href="#" id="one"> Test</a> </li>
<li><a href="#" id="two"> Test again</a> </li>
<li><a href="#" id="three">Tester </a></li>
<li><a href="#" id="four"> Testify</a> </li>
</ul>
<script>
var first = document.getElementById('one');
var second = document.getElementById('two');
var third = document.getElementById('three');
var fourth = document.getElementById('four');
var colorChange = function(theID) {
this.id = theID;
this.formatContent = () => {
this.id.style.color = "red";
};
}
test = new colorChange(first);
testAgain = new colorChange(second);
tester = new colorChange(third);
testify = new colorChange(fourth);
function createEventListeners() {
if (first.addEventListener) {
first.addEventListener("click", test.formatContent, false);
}
if (second.addEventListener) {
second.addEventListener("click", testAgain.formatContent, false);
}
if (third.addEventListener) {
third.addEventListener("click", tester.formatContent, false);
}
if (fourth.addEventListener) {
fourth.addEventListener("click", testify.formatContent, false);
}
}
function init() {
createEventListeners();
}
if (window.addEventListener) {
//call init() on page load
console.log("> Adding TC39 Event Listener...");
window.addEventListener("load", init, false);
} else if (window.attachEvent) {
console.log("> Adding MS Event Listener...");
window.attachEvent("onload", init);
}
</script>
</body>
</html>
您会注意到,当您单击其中一个 li 项目时,它的颜色会变为红色。问题是,当您单击另一个 li 时,这并不清楚。我的想法是,我可以告诉浏览器在运行 formatContent() 时将所有其他对象更改为黑色。是否有捷径可寻?
如果需要,这里有一支笔:https://codepen.io/seanbarker182/pen/JexPVz
提前感谢您的帮助!
【问题讨论】:
-
你还没有添加任何代码来清除它。
-
是的,我意识到那里没有任何东西可以改变颜色,所以我不应该期望它在当前状态下清除。我希望得到一些关于清除它的最佳方法的建议。
标签: javascript jquery html css object