[英]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? 有什么办法吗?
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
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 ? 但是,为什么需要这样做呢?
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.