multiple instances of the same jquery script
if i have a script but it needs to run multiple times on a page, like in a cms for example, how do you approach this? in one experiment i had the code run multiple times but i put the article id on the end of the selectors that would fire off commands and what needed to be manipulated. it's not a good workaround though cause there's too much duplication of code (even though it works).
here is the example that i got help with in a recent stack overflow discussion (with the article ids appended(textpattern)):
<script type="text/javascript">
$(document).ready(function() {
$('.fullTracksInner<txp:article_id />').hide();
$('.tracklist&开发者_JAVA技巧lt;txp:article_id />').click(function() {
$('.fullTracksInner<txp:article_id />').slideToggle('medium');
if ($('.fullTracksInner<txp:article_id />').is(':hidden')) {
$(this).text('Show Tracklist');
} else {
$(this).text('Hide Tracklist');
}
});
});
</script>
just imagine for example three slideshows on a page using the same slideshow script.
This is a relatively common task to do in jQuery. In order for this to work for multiple elements on the same page without requiring unique IDs, you just need to use $(this)
in order to define the relative element you're acting on. I don't know what you're markup looks like, but you could probably do something like the following:
$(document).ready(function() {
$('.fullTracksInner<txp:article_id />').hide();
$('.tracklist<txp:article_id />').click(function() {
$(this).children('.fullTracksInner<txp:article_id />').slideToggle('medium');
if ( $(this).children('.fullTracksInner<txp:article_id />').is(':hidden') ) {
$(this).text('Show Tracklist');
} else {
$(this).text('Hide Tracklist');
}
});
});
You should probably modify your selectors a little though, I would think that $('.tracklist<txp:article_id />')
might choke in some browsers.
You could extract the repeating code to standard JavaScript methods and then call them wherever desired.
<script type="text/javascript">
function performSlide(tracklist) {
var fulltracks = $('.fullTracksInner<txp:article_id />');
$(fulltracks).slideToggle('medium');
if (fulltracks).is(':hidden')) {
changeText(tracklist, 'Show Tracklist');
} else {
changeText(tracklist, 'Hide Tracklist');
}
}
function changeText(textbox, text) {
textbox.text(text);
}
$(document).ready(function() {
var tracklist = $('.tracklist<txp:article_id />');
tracklist.click(function() {
performSlide(tracklist);
});
$('.someRadioButton').change(function() {
performSlide(tracklist);
});
});
</script>
精彩评论