1

私はコードの次のスニップを持っています:

var about = "about.html";

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

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

のようなボタンをクリックすると<li class="about">targetis = aboutになります。
しかし、そのように、$("#dashboard").load(target);ロードしたいhtmlファイルに関する変数をロードしません。

では、この方法で変数を呼び出すにはどうすればよいでしょうか。

4

5 に答える 5

3

.htmlあなたはその部分を見逃しているようです。試してみてください

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

ただし、要素にクラスが 1 つしかない場合は、.よりも.liを使用する方がよいでしょう。this.className$(this).attr("class")

編集 :

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);
});
于 2013-06-24T12:45:52.823 に答える
1

ばかげた答え:<a>タグを作成し、そのhref属性を正しい値に設定します。

さもないと :

ペアを 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);
}
于 2013-06-24T12:55:58.567 に答える
0

次のようなオブジェクトまたは配列参照として「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"));
});
于 2013-06-24T12:59:29.263 に答える
0
$(".nav li").click(function(){
    loadPage($(this).attr("class") + ".html");
});

また

$("#dashboard").load(target+".html");
于 2013-06-24T12:46:03.213 に答える
0

次のように変数を呼び出すことができます(それがあなたが求めたものである場合):

var test = 'we are here';
var x = 'test';
console.log(window[x]);

PHP の $$ に似ています。出力は次のようになります。

we are hereコンソール ウィンドウで。

于 2013-06-24T12:46:32.703 に答える