文本由于锚标记而刷新页面时突出显示不可见

时间:2013-12-19 10:23:50

标签: jquery html django html5

我的导航栏显示django项目中的主页,住宿,照片库,联系人等选项。

我想突出显示点击的当前标签,但是由于锚标签,onClicking更改是不可见的:

HTML CODE:

 <nav class="main-navigation">

      <ul id="navigation">
        <li class="current-menu-item current_page_item"><a href="{% url url_name m.vertical m.name 'home' %}"><strong>Home<span>welcome</span></strong></a>
         </li>
        <li class="current-menu-item current_page_item"><a href="{% url url_name m.vertical m.name 'accommodation' %}"><strong>Accommodation<span>rates &amp; reservation</span></strong></a>
          <ul class="sub-menu">
          {% for room in m.rooms %}
            <li><a href="{% url url_name m.vertical m.name 'accommodation-single' %}?id={{room.id}}">{{room.title}}</a></li> 
           {% endfor %} 
          </ul>
        </li>
        <li class="current-menu-item current_page_item"><a href="{% url url_name m.vertical m.name 'features' %}"><strong>Photo Gallery<span>Moments in Hotel</span></strong></a>
        </li>
        <!-- li><a href="{% url url_name m.vertical m.name 'events' %}"><strong>Occasions<span>upcoming events</span></strong></a></li-->
        <li class="current-menu-item current_page_item"><a href="{% url url_name m.vertical m.name 'contact' %}"><strong>Contact Us<span>get in touch</span></strong></a></li>
      </ul>

    <!-- .main-navigation -->
    </nav>

使用Jquery:

<script type="text/javascript">
$(document).ready(function(){
 $('#navigation li').click(function() {
       console.log($(this))
        $(this).parent('ul').children('li').css('color','gray');
        $(this).css('color','red'); 
 });
});
</script>

在刷新页面中保持更改的任何技巧?

1 个答案:

答案 0 :(得分:0)

显然,由于锚链接将执行新的http请求,因此更改将不起作用。您可以编写模板标记来检查特定链接是否处于活动状态,然后应用一些自定义样式:

from django import template
from django.core.urlresolvers import reverse

register = template.Library()

@register.assignment_tag(takes_context=True)
def is_link_active(context, *args, **kwargs):
    request = context['request']
    url = kwargs.pop('url', None)
    if not url:
        url_name = args.pop(0)
        url = reverse(url_name, args=args, kwargs=kwargs)
    if request.path == url:
        return True
    return False

然后在模板中你可以这样做:

{% is_link_active url_name m.vertical m.name 'contact' as active %}

<a href="{% url url_name m.vertical m.name 'contact' as active %}" {% if active %}style="color: red"{% endif %}>ABC</a>

OR

{% url url_name m.vertical m.name 'contact' as my_url %}
{% is_link_active url=my_url as active %}

<a href="{{ my_url }}" {% if active %}style="color: red"{% endif %}>ABC</a>