最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论