3 = ??? cancelEvent? (Should be added to the function in 4 I guess)
4 =
function setLink (lnk) {
document.getElementById('scrapetarget').value = lnk;
}
And I have an initialisation code of
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
addLoadEvent (doLinks);
Wrapping it all together …
<script type="text/javascript">
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function setLink (lnk) {
document.getElementById('scrapetarget').value = lnk;
}
function doLinks() {
var links = document.getElementsByTagName('A');
for (var i=0; i<links.length; i++) {
links[i].onclick = setLink (links[i]);
}
}
addLoadEvent (doLinks);
</script>
What’s behind the question is a screen scraper test I’m doing, whereby I call a website address via a form, and clicking on any page link should put the target address into the form and then submit it. I think I’m on the right tracks - it’s just cancelling the original click event I’m not sure about.
Adding to what Stomme said, I’d use this as it makes it neater, and a small improvement to the for loop by not having to find links.length every iteration. Finally, your setLink function will work, but for consistency’s sake I would actually access the href attribute directly:
function setLink () {
document.getElementById('scrapetarget').value = this.href; // this is the element clicked
return false; // cancel default action
}
function doLinks() {
var links = document.getElementsByTagName('A');
for (var i=0, j = links.length; I < j; i++) {
links[i].onclick = setLink;
}
}
This test requires the target link to be entered into a form, which is then automatically submitted. The form uses POST - if GET is used (such as passing the target link via a querystring) then the firewall catches the keywords in the link and blocks the target … using POST circumvents this.
That’s why I’m not sure about return false … I’ve to submit the form before I can use the return, so I’m not sure whether I’ll get a race condition - will the form submit before the link click action tries to fire?