Can't access function inside dynamically added script source

S

sylver

Hi,

Following the discussion that can be found here:
http://groups.google.com/group/comp...y+add+a+script+source&rnum=1#909da813c8527282

I modified mine and was trying to launch an alert message inside the
dynamically added script [data.js].

My sample codes
================================================
[data.js]

var remoteValue = 'Blah blah';
alert('File loaded... ' + remoteValue);

function alertME()
{
alert('alertME in data.js');
}


HTML:
<a href="#" onclick="addScript('data.js');">START</a>

<script type="text/javascript">
var x = 'im blank';
alert(x);
function addButton()
{
var oButton = document.createElement('input');
oButton.value = 'Add script element';
oButton.setAttribute("onclick", "alertME();");
oButton.type = 'button';
document.body.appendChild(oButton);
}

function getValues(x)
{
alert(x);                 // Shows 'removeValue'
setTimeout('alert('+x+')',0);  // Shows 'Blah blah'
}

function addScript(uri)
{
var oScript = document.createElement('script');
oScript.src = uri;
//var head = document.getElementsByTagName('head')[0];
//head.appendChild(oScript);
document.body.appendChild(oScript); //-> head or body, both works
in Firefox 2.0.0.4

addButton();
}
</script>

The alert messages for 'x' appeared correctly. But Firebug return this
error: alertME is not defined, and 'alertME in data.js' never appear.

Is this a limitation in Javascript? Or Did I miss out on something
important?

Your suggestion are trully appreciated.
Thanks.
 
S

sylver

try this instead

oButton.onclick = function() {alertME();};

Thanks for your reply.

I have tried that line of code before and strangely, it didn't work.
That's why I replaced it with oButton.setAttribute("onclick",
"alertME();");

The above code does actually work. I missplaced the correct "data.js"
inside another folder. After placing it inside the correct folder, it
works like a charm.

Thanks for your time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,187
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top