How do I make the below function more dynamic for example commentLink and commentContainer will have an ID after them like this commentLink-2289 commentContainer-2289 because there will be multiple ones in a list.
Javascript
$(function() { $('#commentLink').click(function() { $('#commentContainer').toggle(); if ($('#commentContainer').is(':visible')) { $('#commentContainer').load($(this).attr('href')); } else { $('#commentContainer').html('Loading...'); //Or just leave it as is... } return false; //Prevent default action }); });
Html
<div id='SystemNews'> <ul id='dc_news'> <li> <a href='/Home/SystemNews/69' id='commentLink-0'>Comments</a> <div id='commentContainer-0' style='display:none;'> Loading...</div> </div> </li> </ul> </div>
Note: Please provide a working example, I learn best by example thanks
Try this:
But It would help if you can post the html or a link to the html so we can see what the format you are working with is. I have no idea if the error you are getting is from my code or yours (since my code is just a mod of yours). Which line number is the error on in the script?
Edit My original code had a bug with the this.id.match line, that’s been fixed above, try it now.
Edit : Also, there is an extra closing
</div>in your provided HTML, not sure if that’s a typo or not, but it should be removed.The click event should be wrapped in $(document).ready(function(){ … }); so that jquery can accurately access the dom (since you are querying for
<a>and<div>elements). I’m getting a problem where the lastreturn false;is not being reached, I suspect it has something to do with the is(:visible) code. What is the intended function of that if/else block?