jQuery call function from a string
This question already has an answer here:
您可以使用括号表示法使用包含标识符的字符串访问成员:
var target = 'next';
$("foobar")[target](); // identical to $("foobar").next()
If you're wanting to use jQuery, the answer is quite elegant. Because jQuery is an object (which can be accessed like an array) - you can use $("selector")[target]()
.
Examples:
var target = 'next';
jQuery("selector")[target]();
This will work if you know that you can trust the input. However, if you're not sure of this, you should check that the function exists before trying to run it otherwise you'll get an error.
var target = 'doesNotExist';
if (jQuery.isFunction(target)) {
jQuery('selector')[target]();
}
In my case I needed to get the value from a rel attribute and then parse it as a function, this worked for me.
$jq('#mainbody form').submit(function(e){
var formcheck = $jq(this).attr('rel');
if (typeof window[formcheck] === 'function'){
formok = window[formcheck]();
e.preventDefault();
}
});
function maincheck(){
alert("Checked");
return false;
}
and the form
<div id="mainbody">
<form action="mainpage.php" method="post" rel="maincheck">
<input type="hidden" name="formaction" value="testpost">
<label>Field 1 <input type="text" name="field1" value="<?=$_POST['field1'];?>"></label><br>
<label>Field 2 <input type="text" name="field2" value="<?=$_POST['field2'];?>"></label><br>
<input type="submit" value="Submit Form">
</form>
</div>
链接地址: http://www.djcxy.com/p/94822.html
上一篇: 调用JavaScript函数名称在变量中
下一篇: jQuery从一个字符串调用函数