admin管理员组文章数量:1332339
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 badges5 Answers
Reset to default 7I 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
本文标签: jqueryExecute HTML5 data string as JavaScript (without eval)Stack Overflow
版权声明:本文标题:jquery - Execute HTML5 data- string as JavaScript (without eval)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742329341a2454369.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论