2013-11-04 39 views
2

我已经创建了一个函数来获取网页的路径名,如果它匹配菜单项的id,那么它会添加一个css属性到div标记,显示div作为当前页面。继承人网站即时测试:http://kwp.host22.com。即时通讯使用警报来检查变量是否正确。继承人我的HTML。.css jquery属性不应用css到div标记

<div id="navigation"> 
     <a href="index.html"><div class="navblocks" id="index.html"><p>Home</p></div></a> 
     <a href="cleaning.html"><div class="navblocks" id="cleaning.html"><p>Cleaning</p></div></a> 
     <a href="contact.html"><div class="navblocks" id="contact.html"><p>Contact Us</p></div></a> 
    </div> 

和继承人我的jquery:

var path = window.location.pathname; 
     if(path === "/") 
      { 
      var pathname = path.replace("/","index.html"); 
      } 
     else 
      { 
      pathname = path.replace("/",""); 
      } 
     alert("pathname = " + pathname); 
     var id = "#" + pathname; 
     alert("id = " + id); 
     $('a').each(function() 
      { 
      var href = $(this).attr("href"); 
      alert("href = " + href); 
      if (href === pathname) 
       { 
       $(id).css('box-shadow','0px 0px 20px inset'); 
       } 

,但它不是应用盒子阴影div标签。

任何帮助将不胜感激即时通讯仍然学习jquery。 谢谢

回答

1

这个问题似乎是与您正在使用的ID,如#index.html,然后#clean.html选择正确的DOM元素。这是不正确的,你应该真的只是使用#index和#cleaning,因为这些是有效的ID(在ID中使用。是非法的HTML/XHTML)。解决此获得的

的一种方法是分裂这样的ID,这样你就可以只使用HTML文件名,而不是包括文件扩展名:

var path = window.location.pathname; 
     if(path === "/") 
      { 
      var pathname = path.replace("/","index.html"); 
      } 
     else 
      { 
      pathname = path.replace("/",""); 
      } 

     pathname = pathname.split("."); 
     var id = "#" + pathname[0]; 

     alert("id = " + id); 
     $('a').each(function() 
      { 
      var href = $(this).attr("href"); 
      alert("href = " + href); 
      if (href === pathname) 
       { 
       $(id).css('box-shadow','0px 0px 20px inset'); 
       } 

现在,您将使用#INDEX而不是#index.html作为文件扩展名已被删除。要做到这一点,我已经添加的代码是:

pathname = pathname.split("."); 
var id = "#" + pathname[0]; 

来源:http://www.w3schools.com/jsref/jsref_split.asp

3

问题是jQuery会将id“#index.html”解释为“带id索引和html类的元素”。你不需要在你的ID中使用点来实现这个功能,或者避开点。

或者,你可以做一个属性选择,是这样的:

$("[href='"+pathname+"']").find('.navblocks').css('box-shadow','0px 0px 20px inset'); 

这将是少了很多工作的总体

2

的问题是你的id.。你需要为了逃避这个jQuery的读它作为一个ID而不是一个ID,然后一类选择:

id = "#index\\.html" 

为此,您可以使用:

var id = "#" + pathname.replace('.', '\\\.'); 

如果我们内部测试这个你的页面上的JavaScript控制台,我们可以得到以下结果:

Working Example