jquery - 如何突出菜单链接单击? [英] jquery - How to highlight a menu link when clicked?

查看:81
本文介绍了jquery - 如何突出菜单链接单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有链接的菜单。链接放置在表中。每个链接都放置在< td> 中。我想改变< td> 的背景颜色。



这是指向我的代码的链接: http://jsfiddle.net/DdG8m/



我的问题是,如果一个链接被点击的整体的背景颜色表更改。请帮忙。提前感谢。

解决方案

您应该参考当前元素,而不是所有与您的选择器匹配的元素。

  $(#mainMenu td)click(function(){
$(this).css('background-color' '#EDEDED');
});

我也建议你使用CSS类,而不是这样设置CSS属性。 p>

这将是类似的;

  $(#mainMenu td ).click(function(){
$(this).addClass('selected');
});

一起

  #mainMenu td.selected {
background-color:#EDEDED;
}

EDIT


psuedo选择器:visited 只能用在链接( a ),



创建 jsFiddle 使用 ul 列表而不是表和 display:block li 元素的链接上填充



我也使用 event.preventDefault()不跟随链接,因为这可能将重新加载页面,并且不包括所选/活动链接的类。

  $($)如果您要跟踪链接并重新加载页面,请使用服务器端代码来呈现该HTML。 #mainMenu a)。click(function(e){
e.preventDefault(); //不要跟随链接
$(#mainMenu a)。removeClass ; //删除所有菜单项上的类
$(this).addClass('selected'); //将类添加到当前菜单项
});


I have a menu with links. The links are placed inside a table. Each link is placed in a <td>. I want to change the background color of the <td> when its active. How am I gonna do it in jquery?

Here is the link to my code: http://jsfiddle.net/DdG8m/.

My problem is that if one the links is clicked the background color of the whole table changes. Please help. Thanks in advance.

解决方案

You should refer to the current element and not all elements matching your selector.

$("#mainMenu td").click(function() {
    $(this).css('background-color', '#EDEDED');
});

I´d also recommend you to use CSS classes instead of setting the CSS properties this way.

That would be something like;

$("#mainMenu td").click(function() {
    $(this).addClass('selected');
});

together with;

#mainMenu td.selected {
  background-color: #EDEDED;
}

EDIT

The psuedo selector :visited should only be used on links (a) and you should not use tables more than you really need to.

Created a jsFiddle that uses an ul list instead of the table and display: block on links to fill the entire parent li element.

I´m also using event.preventDefault() to not follow the link as this probably would reload the page and not include the class for the selected/active link. If you want to follow the link and have the page reload you should use server side code to render that HTML.

$("#mainMenu a").click(function(e) {
    e.preventDefault(); // Don´t follow the link
    $("#mainMenu a").removeClass('selected'); // Remove class on all menu items
    $(this).addClass('selected'); // Add class to current menu item
});

这篇关于jquery - 如何突出菜单链接单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆