How to use Jquery Hide/Show with a foreach loop in PHP
I want to have a read more section that expands without linking to another page so I am trying to implement the Jquery Show/Hide.
The data to be expanded is coming from a foreach loop in php and I have created a function that adds the html markup if the content is long enough
The problems that I am having is that if I click on one of the read more links, it expands all of them and it also scrolls to the top of the page away from where I need the browser to be.
How do I make this work for only the link that is clicked. Is there a way to add varibles from PHP to Jquery?
The Jquery script in the HTML head
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('name#read').hide();
$('a#read_more').click(function(){
$('name#read').slideDown('slow');
});
$('a#read_less').click(function(){
$('name#read').slideUp('slow');
});
});
</script>
The PHP function
开发者_开发技巧function read_more($content){
if (strlen($content) < 150){
return $content;
} else {
$content = substr($content,0,150) . "......<a href='#' id='read_more'>read more</a>" . "<a name id='read'>" . substr($content,150) . "</a>";
return $content;
}
}
What you are looking for is this: http://api.jquery.com/event.stopPropagation/ Use event.stopPropagation() within your click handler so that it'll stay on the same page.
As for the multiple show(s) happening it's probably because you are NOT generating unique ids!! Have either data-* attributes in your html tag or augment a unique id to your 'a' tags. Something like this should work:
$('a.readMore').click(function() {
event.stopPropagation();
var data_id = $(this).data('contentId');
$('#'+data_id).show(); //or fadeIn or slideUp/Down...
}
Your HTML would then be something like this:
<a href="#" class="readMore" data-contentId="1">...read more</a>
<div id="1">My Content to show goes here</div>
Need not be a div, but you get the idea...
精彩评论