...

View Full Version : New to js and Ajax in particular. Why is my <a> ignoring the attached function?



barophobia
07-29-2006, 07:46 AM
Hello,

I'm using the latest versions of Behaviour and Prototype for my experiment so I will not be posting the code for these.

I am trying to get a js function to execute onclick by attaching to an <a> tag through Behaviour.

When the page loads I can click the button and I'll successfully get my Ajax response. If I click the link called "1" I'll be taken to the page defined in the href of the element. However if I simply change the <a> to an <li> and refresh the page I can successfully get my Ajax response.

For some reason (probably painfully obvious to some of you) my <a> tag ignores the attached function. What am I missing?


Thanks!
Chris.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" media="screen" href="lib/css/general.css" />
<script src="prototype-1.4.0.js" type="text/javascript"></script>
<script src="behaviour.js" type="text/javascript"></script>
</head>

<script>
function getHTML()
{
var url = 'test_1_html.php';
var pars = 'someParameter=ABC';

var myAjax = new Ajax.Updater(
'placeholder',
url,
{
method: 'get',
parameters: pars
});
}

var myrules = {
'#link1' : function(element){
element.onclick = function(){
// Your onclick event goes here - eg;
// load a page - do an AJAX etc.;
getHTML(this.href);
}
}
};

Behaviour.register(myrules);
</script>

<input type="button" value="GetHtml" onclick="getHTML()">

<a id="link1" href="test_1_html.php?value=2">1</a>
<div id="placeholder"></div>

<body>

</body>
</html>

_Aerospace_Eng_
07-29-2006, 08:19 AM
Try return false; in your getHTML function. The link might be going to the href before it gets the url.

Kor
07-29-2006, 08:24 AM
Maybe this:
element.onclick = function(){
// Your onclick event goes here - eg;
// load a page - do an AJAX etc.;
getHTML(this.href);return false
}
Your a element do not ignore the function. It just follows the normal default HTML action and open the href. When using the li element, href becomes a simple attribute, with no HTML action, as li element can not open a link with href attribute.

barophobia
07-29-2006, 08:37 AM
Maybe this:
element.onclick = function(){
// Your onclick event goes here - eg;
// load a page - do an AJAX etc.;
getHTML(this.href);return false
}


Ahh.. success!


Thank you!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum