Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Variables Javascript

I am trying to pass a variable in javascript. I create a link in the following manner and everything seems to be working.

label.innerHTML = '<a href="#" onclick="show_box(this);"> link</a>';

However when I create the link in the following way where the link would also pass an associated object I get the following error from firebug -> "missing ] after element list"

label.innerHTML = '<a href="#" onclick="show_box(this,'+object+');"> link</a>';

Is this an acceptable way to pass an object to a function. The problem is that I am creating this link within a function. The function creates links like this based upon an object that is passed to it. Therefore I cannot have this "object" as a global scope.

like image 295
slimbo Avatar asked Feb 25 '23 04:02

slimbo


1 Answers

You are building the script by mashing together strings, as such you can only work with strings and object will be automatically stringified.

Use DOM instead.

var link = document.createElement('a');
link.href = "#"; // Have a more sensible fall back for status bar readers and middle clickers
link.appendChild(document.createTextNode(' link');
link.addEventListener('click',function () { show_box(this, object); },false);
label.appendChild(link);

… but use a library that abstracts away the non-standard event models that some browsers have.

like image 83
Quentin Avatar answered Feb 26 '23 20:02

Quentin