jquery string to function convert

妖精的绣舞 提交于 2019-12-02 02:17:23

问题


is this possible?

<div id="anything">I will change</div>
<div id="id" jq="$('#anything').css({background: 'red'})"></div>

var x = '$('#id').attr('jq')';
jQuery.call(x);

Basically i would like use an attribute jq on any tag to act like a onclick would on html that calls the javascript statements.

btw jQuery.call() is for demonstration purposes it doesn't work...


回答1:


You would use eval() but what you are doing seems like a really bad idea:

var x = $('#id').attr('jq');
eval(x);

The reason this is bad, is you are not separating function from structure. HTML is meant to describe structure, not interactivity and function.

JavaScript is meant to provide that interaction and enhancement, but not structure. Using the jQuery inline like that is a violation of that separation. Just food for thought...




回答2:


you can use new Function MDN

body:

<div id='MyFunc' func="alert('Hello!');" >On Load raise an Alert</div>

js:

var myFunc = myFunc || document.getElementById('MyFunc'),
        hello = new Function( myFunc.getAttribute('func'));
    hello.call(this);

give it a try:

http://jsfiddle.net/msLsy/

Hope it helps!



来源:https://stackoverflow.com/questions/2060634/jquery-string-to-function-convert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!