Reputation: 1411
I'm currently using the following javascript to load items in a a few div's:
<script>
$.ajax({
url: 'load.php?type=divA',
cache: false,
success: function(data){
$('#divA').html(data);
}
});
$.ajax({
url: 'load.php?type=divB',
cache: false,
success: function(data){
$('#divB').html(data);
}
}); </script>
HTML:
<div id="divA">
<!-- Load divA item here -->
</div>
<div id="divB">
<!-- Load divB item here -->
</div>
I'm looking (and think) there's a better way to do this. Similar to this: 1 function for a div's, which automatically loads the items in (multiply) div's:
function loadItem(<DIV ID>) {
$.ajax({
url: 'load.php?type=<DIV ID>',
cache: false,
success: function(data){
$('<DIV ID>').html(data);
}
});
};
Upvotes: 0
Views: 209
Reputation: 74738
I think this is better:
function loadItem(div) {
$.ajax({
url: 'load.php?type='+div,
cache: false,
success: function(data){
$('#'+div).html(data);
}
});
};
$(function(){
$('div[id^="div"]').each(function(){
loadItem(this.id);
});
});
What this code is doing:
div
and pass that id to the function.This is a late reply:
$('div[class*="div"]').each(function(){ // class contains div
loadItem(this.className.split(' ')[1]);
});// split by ' ' space and pass the second index as arrays are 0 based index.
Upvotes: 1
Reputation: 5795
It can be done like this:
function loadItem(divId) {
$.ajax({
url: 'load.php?type=' + divId,
cache: false,
success: function (data) {
$('#' + divId).html(data);
}
});
};
Upvotes: 1