简体   繁体   中英

How to call textual function in javascript / jQuery?

For example:

<input id="#me" type="button" callme="doAction()"/>
    
<script>
     var result = callFunction( $("#me").attr('callme') );       /// ?????????
</script>

Try this:

<script>
    var callMe = $("#me").attr("callme");
    var result = eval(callMe);
</script>

If the attribute callme is the name (identifier) of a function just use

<input id="#me" type="button" callme="doAction"/>
(window[$("#me").attr('callme')] || function() {})();

so you can avoid using an expensive eval() .

A better solution would be to not include the function in your HTML markup. It is almost always better to separate your markup from your scripting.

Instead consider adding it to your dom object using

$('#me').data('callme', function(){...});

or

$('#me').data('callme', doAction);

and calling it using

$('#me').data('callme')()

or a little safer

($('#me').data('callme')||jQuery.noop)()

See the jQuery documentation for more details on the data function.

I think maybe this is the solution:

<script>
setTimeout( $("#me").attr('callme'), 0 );
</script>

But how to get the returned value??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM