I have a link that looks like this:
<a id="mylink" onclick="deleteHike( 3 );" href="javascript:void(0);">Yes</a>
It is able to call this JavaScript:
window.onload = function()
{
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function( hike_id )
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
}
But the value that comes in is [object MouseEvent], not the number that I was expecting. Any idea why this happens and how to fix this? 🙂
Thanks!
You are trying to assign the function to your link in two different and conflicting ways.
Using the eval-ed function string,
onclick = "function(value)", works but is deprecated.The other way of binding the click handler in the
onloadevent works too, but if you want a particular value to be passed, you’ll have to change your script a bit because the value as given in the initialonclickis completely lost when you set theonclickto a new function.To make your current method work, you don’t need an
onloadhandler at all. You just need this:To do it the second way, which I recommend, it would look like this:
with this script:
The parameter of a DOM event function is the event object (in Firefox and other standards-compliant browsers). It is nothing in IE (thus the need to also grab window.event). I added a little helper function for you that creates a closure around your parameter value. You could do that each time yourself but it would be a pain. The important part is that getCall is a function that returns a function, and it is this returned function that gets called when you click on the element.
Finally, I recommend strongly that instead of all this, you use a library such as jQuery because it solves all sorts of problems for you and you don’t have to know crazy JavaScript that takes much expertise to get just right, problems such as:
onloadevent fires with the simulated eventready. For example, maybe an image is still downloading but you want to put the focus on a control before the user tries to use the page, you can’t do that withonloadand it is a really hard problem to solve cross-browser.Note: in your click handler you can just use the
thisevent which will have the clicked element in it. This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element’sonclickevent, you can simply bind the same handler to all your items and get its value from the element. This is better because it lets you encode the information about the element only in the element, rather than in the element and the JavaScript.