jquery 按名称调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1904687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery call function by name
提问by kusanagi
i have function
我有功能
<script type="text/javascript">
$(function () {
$("#search").click(function() {
var text = $("#searchText").val();
$.getJSON("Search", { world: text, filter: text }, function(data) {
$("tr.DataRow").toggle(false);
for (i = 0; i < data.length; i++) {
$("#obj" + data[i]).toggle(true);
}
});
})
});
</script>
now i have another function
现在我有另一个功能
<script type="text/javascript">
$(function() {
$('#searchText').bind('keypress', function(e) {
if (e.keyCode == 13) {
}
});
});
</script>
how can i call first function from second function?
如何从第二个函数调用第一个函数?
回答by Juan
You can raise a click event on the element you registered the first function
您可以在注册第一个函数的元素上引发单击事件
<script type="text/javascript">
$(function() {
$('#searchText').bind('keypress', function(e) {
if (e.keyCode == 13) {
$('#search').click(); // Raise a click event on #search element
}
});
});
</script>
回答by harto
Extract the logic from the first event handler into a named function:
将第一个事件处理程序的逻辑提取到命名函数中:
function doSearch() {
var text = $("#searchText").val();
$.getJSON("Search", { world: text, filter: text }, function(data) {
$("tr.DataRow").toggle(false);
for (i = 0; i < data.length; i++) {
$("#obj" + data[i]).toggle(true);
}
});
}
You can now pass doSearch
by name to the click handler:
您现在可以doSearch
按名称传递给点击处理程序:
$(function () {
$("#search").click(doSearch);
});
and explicitly invoke it from within the key handler:
并从密钥处理程序中显式调用它:
$(function () {
$('#searchText').bind('keypress', function(e) {
if (e.keyCode == 13) {
doSearch();
}
});
});
回答by Pointy
// first function
$(function() {
$.yourFavoriteFunctionName = function() {
// the code for the first function
};
$.yourFavoriteFunctionName();
});
then
然后
// second function
$(function() {
// whatever
if (foo)
$.yourFavoriteFunctionName();
回答by RamboNo5
you could give it a name? am I missing something?
你能给它一个名字吗?我错过了什么吗?
edit:to get this right
编辑:要做到这一点
<script type="text/javascript">
function() myfunction{
var text = $("#searchText").val();
$.getJSON("Search", { world: text, filter: text }, function(data) {
$("tr.DataRow").toggle(false);
for (i = 0; i < data.length; i++) {
$("#obj" + data[i]).toggle(true);
}
});
}
$(function(){
$("#search").click(myfunction);
});
</script>
and then
进而
<script type="text/javascript">
$(function() {
$('#searchText').bind('keypress', function(e) {
if (e.keyCode == 13) {
myfunction();
}
});
});
</script>