By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,313 Members | 2,725 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,313 IT Pros & Developers. It's quick & easy.

Can't access function inside dynamically added script source

P: n/a
Hi,

Following the discussion that can be found here:
http://groups.google.com/group/comp....9da813c8527282

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.

Jun 20 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a

try this instead

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

Jun 20 '07 #2

P: n/a
On Jun 20, 1:59 pm, Pete <peter.gal...@gmail.comwrote:
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.

Jun 20 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.