【问题标题】:EVAL in jQuery, this is the correct way?jQuery中的EVAL,这是正确的方法吗?
【发布时间】:2010-09-17 23:55:51
【问题描述】:

我需要用EVAL调用一个jQuery函数(但我不知道怎么做),然后我用这个解决方案解决,但我认为这不是正确的方法......

<script>
jQuery.fn.customfunction = function (data) { alert( data ); }
</script>

<div id="eval_div"></div>
<form><input role="button" myFunction="customfunction"/></form>
<script>
$('[role=button]').click( function() {
var button = this;
$.post( "/action",
        $(form).serialize(),
        function (data) {
            $('#eval_div').html( "<script>" + $(button).attr('myFunction')  + "('" +  data   + "');</script>" );
        } );
});
</script>

customfunction是每个表单的通用函数,每个表单都有不同的CUSTOMFUNCTION,名称不同,因此按钮具有函数的名称。

【问题讨论】:

  • 这段代码运行良好..我的问题是:这是正确的方法吗?
  • 没有正确使用eval的方法
  • @Claudiu - 甚至 Crockford 也建议将 eval() 用于 JSON。
  • @Peter:真的吗? evalling 解析 JSON 最终可能会......做任何事情。
  • @Claudiu - 我的错。不知道我从哪里得到的。无论如何,here's some discussion of eval and JSON and why a parser is better...... user439866 - 我意识到这一点。

标签: javascript jquery function eval call


【解决方案1】:

如果你只是想调用函数……你可以很简单地做到:

function (data) {
    jQuery.fn[$(button).attr('myFunction')](data);
};

【讨论】:

    【解决方案2】:

    在这种情况下,您不需要 eval。在 JavaScript 中,您可以使用点表示法或方括号。他们的意思是一样的。试试这条线。

    $('#eval_div').html(jQuery.fn[$(button).attr('myFunction')](data));
    

    【讨论】:

      猜你喜欢
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多