[英]Call Javascript Function with argument and use argument as a variable name
我有以下代码片段:
var about = "about.html";
function loadPage(target){
$("#dashboard").load(target);
}
$(".nav li").click(function(){
loadPage($(this).attr("class"));
});
所以当我点击像<li class="about">
这样的按钮时, target
is = about 。
但就这样, $("#dashboard").load(target);
不加载我要加载的html文件的变量。
那么如何以这种方式调用变量呢?
你似乎错过了.html
部分。 试试吧
$("#dashboard").load(target+'.html');
但是,假设你的li
元素只有一个类,你最好使用this.className
而不是$(this).attr("class")
。
编辑:
如果你想使用你的about
变量,你可以这样做:
$("#dashboard").load(window[target]);
但是拥有地图会更加清晰:
var pages = {
'about': 'about.html',
'home': 'welcome.jsp'
}
function loadPage(target){
$("#dashboard").load(pages[target]);
}
$(".nav li").click(function(){
loadPage(this.className);
});
一个愚蠢的答案:创建一个<a>
标签,并将其href
属性设置为正确的值。
除此以外 :
存储key: values
标准方法key: values
javascript中的key: values
对是使用普通对象:
var urls = {};
urls['about'] = 'mysuperduperurlforabout.html';
function loadPage(target) {
var url = urls[target];
//maybe check if url is defined ?
$('#dashboard').load(url);
}
$(".nav li").click(function(){
loadPage($(this).attr("class") + ".html");
});
要么
$("#dashboard").load(target+".html");
您可以像这样调用变量(如果这就是您所要求的):
var test = 'we are here';
var x = 'test';
console.log(window[x]);
它类似于PHP中的$$。 输出将是:
we are here
在控制台窗口。
您可以将“about”作为对象或数组引用,类似于:
var pageReferences = [];
pageReferences["about"] = "about.html";
var otherReference = {
"about": "about.html"
};
function loadPage(target) {
alert(pageReferences[target]);
alert(otherReference[target]);
$("#dashboard").load(target);
}
$(".nav li").click(function () {
loadPage($(this).attr("class"));
});
这两个警报都会提醒“about.html”引用相应的对象。
编辑:如果您希望基于标记填充对象,您可以执行以下操作:
var otherReference = {};
$(document).ready(function () {
$('.nav').find('li').each(function () {
var me = $(this).attr('class');
otherReference[me] = me + ".html";
});
});
您甚至可以将扩展名存储在其他属性中:
var otherReference = {};
$(document).ready(function () {
$('.nav').find('li').each(function () {
var me = $(this).attr('class');
otherReference[me] = me + "." + $(this).attr("extension");
});
});
更好的方法是简单地将页面引用放在数据元素中:
<li class="myli" data-pagetoload="about.html">Howdy</li>
$(".nav li").click(function () {
loadPage($(this).data("pagetoload"));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.