Issue with Javascript in ASP.NET Webform
I have a list of hrefs inside UL. When a user clicks a link, I need to apply a particular CSS style to that href (i.e. make it 'selected' and make all others 'unselected'). The script I used is given below. But it does not work. Any idea where it went wrong?
Thanks
-
Coaliza Anti-Cardiolipin
Coamatic Antithrombin 开发者_StackOverflow社区
<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>
Though I would like to see the HTML I would strongly suggest that you use a Javascript Framework, jQuery would give you a strong push with much less code.
Just add the script src
to your document
and use only this code
<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>
There is no need to have unselected
class, that's should be the default CSS.
精彩评论