I'm having a problem with adding onClick events to <a>
tags. The attribute is never added at all, but no errors are shown in the JavaScript console. I'm using Firefox 3.0.10.
Here's my code:
<html>
<head>
<script type="text/javascript">
function setAJAXAttributes() {
var domain = new RegExp("(" + window.location.host + ")|(^\\/.*)|(^[\\w\\d]*\\.[\\w\\d]{2,})", "i");
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
if (domain.test(links[i].href)) {
links[i].onClick = "getPage('" + links[i].href + "');";
alert("Added onClick: " + links[i].href);
}
else
links[i].target = "_blank";
}
}
</script>
</head>
<body>
<a href="http://www.daniweb.com">DaniWeb</a><br/>
<a href="http://www.example.com/ajax/test.html">Testing absolute path</a><br/>
<a href="/ajax/test.html">Testing page relative parent path</a><br/>
<a href="test.html">Testing name path</a><br/>
<script type="text/javascript">setAJAXAttributes();</script>
</body>
</html>
I made sure that the conditional statement was working correctly by adding an alert to the onClick portion, and the alerts worked fine. However, the onClick event is never added, not on Firefox or IE7.
It also works fine if I change each <a>
tag's href
to javascript: getPage();
, but I don't want to change what shows in the status bar.