jquery - Execute HTML5 data- string as JavaScript (without eval)? - Stack Overflow

I have the following div:<div id="foo" data-callback="function(){console.log(1)}"

I have the following div:

<div id="foo" data-callback="function(){console.log(1)}"></div>

I want to be able to execute the div's callback string as a JavaScipt function like this:

($('#foo').data('callback'))()

But this obviously won't work. Is there any way to do this?

Here's a JSFiddle.

I have the following div:

<div id="foo" data-callback="function(){console.log(1)}"></div>

I want to be able to execute the div's callback string as a JavaScipt function like this:

($('#foo').data('callback'))()

But this obviously won't work. Is there any way to do this?

Here's a JSFiddle.

Share Improve this question asked Apr 24, 2012 at 19:11 HellaMadHellaMad 5,3946 gold badges33 silver badges54 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

I suggest not storing code as a data- attribute. Make a function, then just store the function name as the attribute.

<script>
function callbackA(){
    console.log(1)
}
</script>
<div id="foo" data-callback="callbackA"></div>

Then you can do window[$('#foo').data('callback')]().

EDIT: If you don't want to do this, you can also make use of the onclick event (or any (built-in) event for that matter).

<div id="foo" onclick="console.log(1)"></div>

Then you can use .prop to get the event (as a function), and then use it.

var callback = $('#foo').prop('onclick'); // get function
$('#foo').removeProp('onclick'); // remove event
callback();  // use function

One, potentially crazy :), solution would be to use js.js. This would be more secure than eval.

If you can alter the html to

<div id="foo" data-callback="{console.log(1)}"></div>

then you can do

new Function($('#foo').data('callback'))()

But why do you need to do it that way ?

What you have can be done using eval, but eval is evil.

Edit:

And some modifiction is required to your HTML,

<div id="foo" data-callback="(function (){console.log(1)})"></div>

JS

eval($('#foo').data('callback'))();

DEMO

You could always use the Function constructor, however, you will need a string containing only your statements. You can either parse your existing string or even better, if you can modify the value of that data attribute at the source. Then you would do

var fn = new Function($("#foo").data("callback"));
fn();

Updated JSFiddle

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742329342a4423394.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信