$("#searchType").on('change', function () {
var selectionAction = {
All: loadAll(),
Competitions: loadAll("competitions"),
Clubs: loadAll("clubs"),
Teams: loadAll("teams")
};
var selection = $("#searchType").find('option:selected').val();
selectionAction[selection]
});见上面的代码。其思想是,当选择等于我的对象中的一个属性时,就会调用相应的函数。
例如,当选择等于Competitions时,我们将调用loadAll("competitions")函数。
相反,我发现,当它进入onChange函数时,它会调用所有函数。
我在这里做错什么了?
发布于 2014-10-28 23:39:35
使用匿名函数进行调用。当前,您正在存储未定义的函数调用的结果。
var selectionAction = {
All: function(){loadAll()},
Competitions: function(){loadAll("competitions")},
Clubs: function(){loadAll("clubs")},
Teams: function(){loadAll("teams")}
};
var selection = $("#searchType").find('option:selected').val();
selectionAction[selection]();// make sure to call the anonymous function或者,如果你喜欢简洁,
$("#searchType").on('change', function () {
loadAll($("#searchType").find('option:selected').val().replace("All","").toLowerCase())
});发布于 2014-10-28 23:46:12
当您指定loadAll()、loadAll("competitions")、loadAll("clubs")等时,实际上您将立即执行该函数。您想要做的是让对象具有非函数调用的属性,如下所示:
var selectionAction = {
All: '',
Competitions: 'competitions',
Clubs: 'clubs',
Teams: 'teams'
};然后做:
var selection = $("#searchType").find('option:selected').val();
loadAll(selectionAction[selection]);并确保您的loadAll函数检查其第一个参数是否存在。
https://stackoverflow.com/questions/26620374
复制相似问题