Reputation: 2243
I'm dynamically getting hyperlinks and paragraphs from the database, and I wish to hide/show the paragraphs. How can I use jquery to show/hide only a hidden paragraph of a particular link, instead of showing all the paragraphs?
<body>
<a href="#">first link</a>
<p>Show this when I click first link</p>
<a href="#">second link</a>
<p>Show this when I click second link</p>
<script>
$( "p" ).hide();
$( "a" ).click(function( event ) {
event.preventDefault();
$( "p" ).show();
});
</script>
</body>
Upvotes: 0
Views: 98
Reputation: 10212
The most easy way is to give each paragraph a unique id and store that in the link as well. Like this (fiddle here)
html
<a href="#" rel="p-1">first link</a>
<p id="p-1">Show this when I click first link</p>
<a href="#" rel="p-2">second link</a>
<p id="p-2">Show this when I click second link</p>
javascript
$('a').on('click', function(e) {
e.preventDefault();
$('#'+$(this).attr('rel')).slideToggle();
});
Other options may be, for example, to find the first child of a certain type (eg a p
, or a p
with a specific class). Whatever way finding the element you want suits you. What is most appropriate for you mostly depends on how your page is structured.
Upvotes: 0
Reputation: 207943
Change:
$( "a" ).click(function( event ) {
event.preventDefault();
$( "p" ).show();
});
to:
$( "a" ).click(function( event ) {
event.preventDefault();
$(this).next().show();
});
Note, you could also toggle between show/hide by using .toggle()
instead of .show()
if you like.
Upvotes: 2