我在UL中有一个href列表。当用户点击链接时,我需要将特定的CSS样式应用于该href(即使其'选中'并使所有其他人'未选中')。我使用的脚本如下。但它不起作用。知道哪里出错了吗?
由于
<script type="text/javascript" language="javascript" >
document.onclick = function(evt) {
var el = window.event ? event.srcElement : evt.target;
var aText = "";
if (el && el.className == "unselected") {
el.className = "selected";
aText = el.innerText;
for (var i = 0; i < document.links.length; ++i) {
var a = document.links[i];
if (a.className == "selected" && a.innerText != aText)
a.className = "unselected";
}
/*
var siblings = el.parentNode.childNodes;
for (var i = 0, l = siblings.length; i < l; i++) {
var sib = siblings[i];
if (sib != el && sib.className == "selected")
sib.className = "unselected";
}*/
}
}
</script>
答案 0 :(得分:3)
虽然我希望看到HTML,但我强烈建议您使用Javascript框架,jQuery会为您提供更少的代码。
只需将脚本src
添加到您的文档
并仅使用此代码
<script type="text/javascript">
// well all the DOM is written in the page and all elements are available do:
$(document).ready( function() {
// for each <a> tag bind the event click and now do:
$("a").click(function() {
// 1st. remove all selected
$("a.selected").removeClass("selected");
// 2nd. assign selected to this clicked element only
$(this).addClass("selected");
// 3rd. let's return true so the <a> tag can jump to the href
return true;
});
});
</script>
不需要unselected
类,这应该是默认的CSS。