0

好的,这就是我想要做的。我有一个 navLink 类,其 ID 为 1 到 x(在本例中为 5,但我的想法是如果需要我可以添加到它)。以及 Selection 类下的 Div,1Div 到 xDiv。div 的切换,以及 navlinks 改变颜色,就好像它使用 CSS 活动标签一样。这在我使用 Home div 并且我不希望其中一个链接启动时非常有效。现在我正在尝试这样做,我需要能够将给定的选择器存储在“活动”变量中。我也在努力做到这一点,所以当点击 navLink 3 号它转到不同的页面时,我遇到了同样的问题。我对 JavaScript 有点陌生,所以我不确定 JS 如何存储变量。这是代码:

$(function() {
  var active = $('#1');

  $('.selection').hide();
  $('#1Div').show();

  $('.navLink').hover(
  function() {
     $(this).css("color","#806ac7"); 
  },
  function() {
      if(this === active) {
        $(this).css("color","#961014");
      } else {
        $(this).css("color","#000000");
      }
      });
  $('.navLink').click(function(e){
    active = this;
    $('.navLink').css("color","#000000");
    $(this).css("color","#961014");
      if(this == '#3') {
        location.href = "./Contact.html"  
      } else {
    $('.selection').hide();
    $('#'+ this.id + 'Div').show();
      }
  });
});

提前感谢你们在这里的堆栈是一个很大的帮助。

编辑:

感谢你目前的帮助。这里要求的是一个示例的链接:http: //jsfiddle.net/fgj6H/ 一切正常,但 navlink 3 上的链接仍在寻求帮助。

4

2 回答 2

0

我认为您的部分问题是 ID必须以 HTML4 中的字母开头,并且必须至少包含一个HTML5 中的字母。ID 不允许以数字开头。我建议将您的 ID 重命名为 id="n1" 并将它们称为

var active = $("#n1");

查看此答案 DOM ID 中允许使用哪些字符?

和 HTML5 规范 http://www.w3.org/TR/html5/dom.html#the-id-attribute

于 2013-06-28T13:27:29.200 回答
0

编辑:

我想你需要这个

if(this.id == 'n3')

而不是这个

if(this == '#n3')

原始答案:

我认为这可能是一个范围问题。

本地范围:

var active = $('#1');

全球范围:

active = this

尝试删除第一个var,使其显示

active = $('#1');

编辑:这是带有一些注释的代码。

  $(function() {
  // *** this variable is defined with "var" keyword, meaning it is only available
  // in the immediate scope i.e. within the braces (it's more complicated than that)
  var active = $('#1');

  $('.selection').hide();
  $('#1Div').show();

  $('.navLink').hover(
  function() {
     $(this).css("color","#806ac7"); 
  },
  function() {
      // *** this can only refer to a global variable, as "var active" is not present in here. The global will not get defined till .navLink is clicked.
      if(this === active) {
        $(this).css("color","#961014");
      } else {
        $(this).css("color","#000000");
      }
      });
  $('.navLink').click(function(e){

    // *** this sets a new global variable "active" and gives it a value
    active = this;
    $('.navLink').css("color","#000000");
    $(this).css("color","#961014");
      if(this == '#3') {
        location.href = "./Contact.html"  
      } else {
    $('.selection').hide();
    $('#'+ this.id + 'Div').show();
      }
  });
});
于 2013-06-28T13:36:12.693 回答