我试图在 jQuery 代码中分配一个字符串作为函数的名称,但我所做的有问题。在下面的代码中,我name="hello"作为函数名和msg="hello world!"参数传递。我正在尝试调用该hello(msg)函数。任何帮助将不胜感激。
HTML
`<input type="button" value="Click me!">`
Run Code Online (Sandbox Code Playgroud)
CSS
input{
width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
jQuery
$(document).ready(function(){
$('input').click(function(){
var name = 'hello';
var msg = 'hello world!';
window[name](msg);
});
function hello(msg){
alert(msg);
}
});
Run Code Online (Sandbox Code Playgroud)
您已经hello使用 dom 就绪处理程序的关闭定义了该方法,因此它不会是 window 对象的属性,只有全局变量/函数可以作为 window 对象的属性访问。
所以要么将其分配为 window 对象的属性
$(document).ready(function() {
$('input').click(function() {
var name = 'hello';
var msg = 'hello world!';
window[name](msg);
});
window.hello = function hello(msg) {
alert(msg);
}
});Run Code Online (Sandbox Code Playgroud)
input {
width: 100px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">Run Code Online (Sandbox Code Playgroud)
或者在闭包之外定义它
$(document).ready(function() {
$('input').click(function() {
var name = 'hello';
var msg = 'hello world!';
window[name](msg);
});
});
function hello(msg) {
alert(msg);
}Run Code Online (Sandbox Code Playgroud)
input {
width: 100px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">Run Code Online (Sandbox Code Playgroud)
但是更合适的方法可以使用与 window 对象不同的对象,例如
$(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);
}
});Run Code Online (Sandbox Code Playgroud)
input {
width: 100px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">Run Code Online (Sandbox Code Playgroud)