且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jquery 字符串到函数转换

更新时间:2023-02-03 08:50:56

你会使用 eval() 但你所做的似乎是一个非常糟糕的主意:

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

这很糟糕的原因是您没有将功能与结构分开.HTML 旨在描述结构,而不是交互性和功能.

JavaScript 旨在提供交互和增强,而不是结构.像这样使用 jQuery 内联违反了这种分离.仅供参考...

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...

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...

相关阅读

技术问答最新文章