简体   繁体   English

执行HTML5数据字符串作为JavaScript(没有eval)?

[英]Execute HTML5 data- string as JavaScript (without eval)?

I have the following div: 我有以下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: 我希望能够将div的回调字符串作为JavaScipt函数执行,如下所示:

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

But this obviously won't work. 但这显然行不通。 Is there any way to do this? 有什么办法吗?

Here's a JSFiddle . 这是一个JSFiddle

I suggest not storing code as a data- attribute. 我建议不要将代码存储为data-属性。 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')]() . 然后,您可以执行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). 编辑:如果您不想这样做,则还可以使用onclick事件(或任何与此相关的(内置)事件)。

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

Then you can use .prop to get the event (as a function), and then use it. 然后,您可以使用.prop获取事件(作为函数),然后使用它。

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 . 一种可能是疯狂的:)解决方案是使用js.js。 This would be more secure than eval . 这将比eval更安全。

If you can alter the html to 如果可以将html更改为

<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 . 您可以使用eval来完成所有操作,但是eval是邪恶的

Edit: 编辑:

And some modifiction is required to your HTML, 而且您的HTML需要进行一些修改,

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

JS JS

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

DEMO 演示

You could always use the Function constructor, however, you will need a string containing only your statements. 您始终可以使用Function构造函数,但是,您将需要一个仅包含语句的字符串。 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 更新了JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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