0

ページのナビゲーションリンクを持つuserControl.htmがあり、IDを持つページがあり、「選択された」クラスを対応するホームリンクに追加したいと思います。

var page =(getElementByID( "someId"))でうまくいくと思いましたが、うまくいきませんでした。

var page = (getElementByID("someId"))    
switch (page) {
case 'home':
    document.getElementById("About").className = "selected";
    break;
case 'about':
    document.getElementById("About").className = "selected";
    break;
case 'contact':
    document.getElementById("contact").className = "selected";
    break;
case 'services':
    document.getElementById("services").className = "selected";
    break;
default:
    document.getElementById("home").className = "selected";
}

ありがとうございました

4

3 に答える 3

2

冗長なコードを記述する代わりに、キーと値のマップを使用することを検討してください。

//value with corresponding, and maybe not 1:1 pair
var pairs = {
  'home' : 'About',
  'about' : 'About',
  'contact' : 'contact',
  'services' : 'services',
  'default' : 'home'
  //you can add as much as you want here
};

//then get your page value
var page = getYourValue();

//page might or might not exist on the pairs list, thus we check
//default to 'default' if non-existent
page = (pairs[page]) ? page : 'default';

//then get from the map the desired value
document.getElementById(pairs[page]).className = "selected";

次のいずれかを使用して、ボディの ID を取得できます。

document.body.id
//or
document.getElementsByTagName('body')[0].id
于 2013-02-10T02:21:30.953 に答える
0

私はjqueryを使わなければなりませんでした

    current_page = document.location.href
if (current_page.match(/index/)) {
    $("#home").addClass("selected");
} else if (current_page.match(/Contact/)) {
    $("#contact").addClass("selected");
} else if (current_page.match(/media/)) {
    $("#media").addClass("selected");
} else if (current_page.match(/About/)) {
    $("#About").addClass("selected");

} else if (current_page.match(/Information/)) {
    $("#information").addClass("selected");
} else { // don't mark any nav links as selected
    $("ul#navigation li").removeClass('selected');
};
于 2013-02-13T04:13:37.503 に答える
0

これを使用するだけです:

document.getElementById(page).className = "selected";

文字列の値をコピーするだけの大きなswitchステートメントの代わりに。

于 2013-02-10T02:20:55.433 に答える