tterbeg
tterbeg

Reputation: 85

How to call a script by id using onclick?

May be obvious but I tried searching and can't figure it out. I am using a third party tool which has a script. The script has an id, but the function within the script has no name. I have a javascript onclick function where all I want to do is call the script by its id from an onClick function.

ie. script is

<script id="feed" type="text/javascript">(function(){...}())</script>

I need to call this script from

$('#searchBox').html("<li onClick=\"$(\"#feed\");\">Click to contact us</li>");

I tried to call the 'feed' script as above but no luck. In case it matters, the 'feed' script is in the body of the page and #searchBox is an auto-suggest box in a search field on that page. Will appreciate any help! Thanks!

Upvotes: 2

Views: 2456

Answers (2)

gen_Eric
gen_Eric

Reputation: 227200

You can try making the un-named function into a named function. By adding a new script tag to the head.

$('<script></scr' + 'ipt>', {
    html: 'function feedback(){' + $('#feed').html() + ' }',
    type: 'text/javascript'
}).appendTo('head');

Or better yet, by using new Function:

var feedback = new Function($('#feed').html());

Then use that function in the click handler in the new DOM element.

$('#searchBox').html($('<li></li>',{
    text: 'Click to contact us'
}).click(feedback));

(I hate using inline JavaScript.)

Upvotes: 2

Sean Johnson
Sean Johnson

Reputation: 5607

I would try this:

$("#searchbox").html("<li onClick=\"eval($(\"#feed\").html())\">Click to contact us</li>")

Assuming that the script in #feed executes on its own, and looks something like this: (function(){...})()

If, however, the function looks exactly as you posted, (function(...){}), this should work:

$("#searchbox").html("<li onClick=\"eval($(\"#feed\").html())()\">Click to contact us</li>")

Upvotes: 2

Related Questions