在jQuery中调用string中的函数

时间:2015-05-18 03:50:45

标签: jquery function

我试图在jQuery代码中指定一个字符串作为函数的名称,但是我正在做的事情有问题。在下面的代码中,我传递name="hello"作为函数名称,msg="hello world!"作为参数。我试图调用hello(msg)函数。任何帮助将不胜感激。

http://jsfiddle.net/7jhveokn/

HTML

`<input type="button" value="Click me!">`

CSS

input{
    width: 100px;
}

的jQuery

$(document).ready(function(){

$('input').click(function(){
    var name = 'hello';
    var msg = 'hello world!';
    window[name](msg);
});

function hello(msg){
    alert(msg);
}
});

3 个答案:

答案 0 :(得分:4)

您已使用dom ready处理程序的闭包定义了方法hello,因此它不是窗口对象的属性,只有全局变量/函数可作为window对象的属性访问。

因此要么将其指定为窗口对象的属性

$(document).ready(function() {

  $('input').click(function() {
    var name = 'hello';
    var msg = 'hello world!';
    window[name](msg);
  });

  window.hello = function hello(msg) {
    alert(msg);
  }
});
input {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">

或者在闭包之外定义它

$(document).ready(function() {
  $('input').click(function() {
    var name = 'hello';
    var msg = 'hello world!';
    window[name](msg);
  });
});

function hello(msg) {
  alert(msg);
}
input {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">

但是更合适的方法可以使用与窗口对象不同的对象,如

$(document).ready(function() {

  $('input').click(function() {
    var name = 'hello';
    var msg = 'hello world!';
    fns[name](msg);
  });

  var fns = {};
  fns.hello = function hello(msg) {
    alert(msg);
  }
});
input {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">

答案 1 :(得分:0)

(文档)$。就绪(函数(){

$('input').click(function(){
    var name = 'hello';
    var msg = 'hello world!';
    //window[name](msg);
    eval(
        'function '+name+'(msg){ alert(msg); }');
    );

});

});

答案 2 :(得分:-1)

window.hello = function(msg) {
  alert(msg);
};