0

I made a navigation bar as tabs in my website, and I used the onlink identity to specify the current tab with certain characteristics. My problem is that when I change tabs, I don't know how to make the previous tab id set as none and the current one set as onlink.

Here's the navigation bar code:

<div id="indNavBar">
<div id="indHolder">
<ul>
<li><a onclick="DisplayDIV('IndPage');HideDIV('DoubleInd')" id="onlink">Single Indicator</a></li>
<li><a onclick="DisplayDIV('DoubleInd');HideDIV('IndPage');">Double Indicators</a></li>
</ul>
</div>
</div>

There's a simple ways but it's somehow stupid, which is to make each current tab as a whole page and when I click another tab, it's just given the url of clicked tab which goes to the page with specified onlink id, but this requires reloading the whole page that's why I'm seeking a better solution.

4

5 回答 5

1

this您可以通过传入javascript方法来获取被点击的控件

onclick="DisplayDIV('IndPage', this);


function DisplayDIV(IndPage, sourceObj)
{
   alert(sourceObj.id);
}
于 2012-07-04T09:52:26.797 回答
0

You are trying to use HTML ids in the wrong way.

Ids are unique identifiers for HTML tags. They should not change at runtime.

Instead, apply CSS classes to the tab you want to be visible.

CSS

.hide {display:none;}

Javascript

var indpage = document.getElementById("IndPage");
if (!indpage.classList.contains("hide")) {
    indpage.classList.add("hide");
}

Then your HTML at runtime will change to

<div id="IndPage" class="hide">...</div>

This is the standard approach.
And you can do much more with this idea.

I agree that making a tab a whole page is not a good idea. You can use javascript to apply CSS classes to hide and remove that class to show again.

Its also a good idea to learn how to separate your javascript from your HTML. Please read some more tutorials on this. One for instance: Unobtrusive Javascript

于 2012-07-04T10:10:50.733 回答
0

Here is a jquery way to do it: http://jsfiddle.net/surendraVsingh/HyAhL/

$('#indHolder a').click(function(){

    $(this).attr('id', 'onlink');
     $(this).parent().siblings().find('a').removeAttr('id');
});​
于 2012-07-04T10:11:43.360 回答
0

Are you ok do use the jQuery Library? If so you can avoid putting inline javascript into your html and use toggleClass http://api.jquery.com/toggleClass/

于 2012-07-04T09:54:32.840 回答
0

我从上面的答案中得到了提示,它的工作原理如下:

function putOnlink(x){
document.getElementById('onlink').id = "none";
$(x).attr('id','onlink');
}

标签代码是:

<div id="indNavBar">
<div id="indHolder">
  <ul>
    <li><a onclick="DisplayDIV('IndPage');HideDIV('DoubleInd');putOnlink(this);" id="onlink">Single Indicator</a></li>
    <li><a onclick="DisplayDIV('DoubleInd');HideDIV('IndPage');putOnlink(this);document.getElementById('onlink').id='none'">Double Indicators</a></li>
  </ul>
</div>
</div>

我只是不想在第二个链接中我不得不更改第一个链接的 id 两次,因为它没有工作一次,可能是因为它的 id 设置在标签中,而不仅仅是在点击时。

于 2012-07-04T10:37:46.837 回答