gpt4 book ai didi

javascript - 使用参数调用 Javascript 函数并将参数用作变量名

转载 作者:行者123 更新时间:2023-11-30 10:30:11 25 4
gpt4 key购买 nike

我有以下代码片段:

var about = "about.html";

function loadPage(target){
$("#dashboard").load(target);
}

$(".nav li").click(function(){
loadPage($(this).attr("class"));
});

所以当我点击像 <li class="about"> 这样的按钮时, target是 = 关于
但是那样的话,$("#dashboard").load(target);不加载有关我要加载的 html 文件的变量。

那么怎么可能这样调用变量呢?

最佳答案

您似乎错过了 .html 部分。试试看

$("#dashboard").load(target+'.html');

但是,假设您的 li 元素上只有一个类,您最好使用 this.className 而不是 $(this).attr( “类”)

编辑:

如果你想使用你的about变量,你可以这样做:

$("#dashboard").load(window[target]);

但是如果有一张 map 会更干净:

var pages = {
'about': 'about.html',
'home': 'welcome.jsp'
}
function loadPage(target){
$("#dashboard").load(pages[target]);
}
$(".nav li").click(function(){
loadPage(this.className);
});

关于javascript - 使用参数调用 Javascript 函数并将参数用作变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17275786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com