flower flower - 3 months ago 9
Javascript Question

Can I use jquery to operate the name attribute of <a> tag?

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?

Answer

Classes are our friend - forget trying to use a name attribute - this is not the correct use for that. What you want to do is add a class and then alter the display based on the class:

//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();

you can also add css in the jquery

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

but the better way of altering the display state is to have a class that you then add or remove to the elements - that way you are not altering the actual css of the element:

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

//js


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

you can also toggle the class - which allows you to show the elements simply by not hiding them //js

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