我可以使用jquery来操作<a> tag?

时间:2016-09-05 13:04:33

标签: javascript jquery

In my web I have more than 5 links,some of them are in the same group. I want to make them hide or show together.So I give the same name to the common link.But How to operate them?

<a href='a.jsp' name='group1'>aa</a>
<a href='b.jsp' name='group2' >bb</a>
<a href='c.jsp' name='group1'>cc</a>
<a href='d.jsp' name='group2'>dd</a>
<a href='e.jsp' name='group1'>ee</a>

If use input,I can write like $("input[name='group1']").hide();.But now is link tag.How to operate them?

2 个答案:

答案 0 :(得分:2)

类是我们的朋友 - 忘记尝试使用名称属性 - 这不是正确的用途。你想要做的是添加一个类,然后根据类改变显示:

//HTML
<a href='a.jsp' class='group1'>aa</a>
<a href='b.jsp' class='group2' >bb</a>
<a href='c.jsp' class='group1'>cc</a>
<a href='d.jsp' class='group2'>dd</a>
<a href='e.jsp' class='group1'>ee</a>

//js
$('.group1').hide();

你也可以在jquery中添加css

//js
$('.group1').css('display','none');

但更改显示状态的更好方法是使用一个类然后添加或删除元素 - 这样就不会改变元素的实际css:

//css
.hidden {display:none}
.shown{display:block}

//js


$('.group1').addClass('hidden');

你也可以切换这个类 - 它允许你简单地通过不隐藏它们来显示元素 // JS

 $('.group1').toggleClass('hidden');

答案 1 :(得分:0)

您可以使用与输入相同的代码选择所有锚标记,但是您只需指定要选择<a>标记,然后可以调用方法hide()

$("a[name='group1']").hide()

代码的[name='name']部分称为CSS属性选择器,它可以与大多数HTML标记一起使用。

看到这个: https://css-tricks.com/almanac/selectors/a/attribute/

这个: https://developer.mozilla.org/cs/docs/Web/CSS/Attribute_selectors

虽然在做这样的事情时,使用类会好得多。