如何挂钩 jQuery 自己的函数,以检查字符串是否可以评估为函数?
我希望能够做到这一点
$('.class').bind({'click':'function(){ ... }'}); // note that the value is a string
,并以某种方式检查挂钩的“bind”内部,它确实是一个函数,以及 eval()
或 new Function
字符串,所以它将被正确分配为事件。
我想这样做的原因是因为 JSON 不允许将函数定义为值,只能定义为字符串/整数。 我想找到一种方法将其应用于以处理程序/函数作为参数的所有 jquery 函数(例如 animate()、click()、live() 等)。我认为这将是一个巨大的麻烦,并且在每个新版本的 jQuery 发布后都会变得不切实际
或者有没有更好的方法来完成这个? 检查前 8 个字符是否 === 'function' 然后 eval 这不是一个好主意,因为它可以是“合法”文本字符串。 我尝试传递一个函数作为 ajax JSON 响应的结果,但 $.parseJSON 默默地失败了。
I want to be able to do this
$('.class').bind({'click':'function(){ ... }'}); // note that the value is a string
and somehow, checking inside a hooked "bind", that it's indeed a function, and eval()
or new Function
the string, so it will be correctly assigned as an event.
The reason I want to do this is because JSON doesn't allow functions to be defined as values, only strings/ints.
I would want to find a way to apply this for all jquery functions (like animate(), click(), live(), etc) that take a handler/function as parameter. it would be a huge hassle and I think, and would become impractical after each new version of jQuery released
Or is there any better way to accomplish this? checking for the first 8 characters if they are === 'function' and then eval it is not a good idea, since it can be a "legitimate" text string.
I tried passing a function as a result from a ajax JSON response, but $.parseJSON failed silently.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是您要找的http://jsbin.com/adewe4/3
函数定义https://gist.github.com/862112
您可以使用
parseJSONwithFunctions
方法使用$.getJSON
解析您作为 AJAX 响应收到的 JSON 数据。parseJSONwithFunctions
将函数体作为 JSON 中的字符串转换为实际的函数对象;因此,您可以将函数引用传递给它,而不是尝试创建 jQuery eval 字符串。如果您使用该方法,
并且您可以将处理程序定义为,
Is this what you are looking for, http://jsbin.com/adewe4/3
function definition https://gist.github.com/862112
You can use the
parseJSONwithFunctions
method to parse the JSON data that you receive as the AJAX response using$.getJSON
.parseJSONwithFunctions
converts the function body as strings in the JSON into actual function objects; so rather than trying to make jQuery eval strings, you can just pass the function reference to it.If you use the method as,
and the you can define handlers as,
刚刚找到我自己的答案,哇,javascript 可以非常强大,检查一下
不需要挂钩任何 jQuery 特定功能。当它尝试对字符串调用 call() 或 apply() 时,它将评估为代码/函数。问题是,这是一个全局修改,如果有人发现它,可能会导致一些客户端破坏,呵呵。
该解决方案有哪些注意事项?
Just found my own answer, WOW, javascript can be quite powerful, check this out
No need to hook any jQuery specific function. When it tries to call() or apply() on a string, it will eval to code/function. the problem is that this is a global modification, and could lead to some client-side havoc if someones find out about it hehe.
what are the caveats in this solution?