jQuery change text in div using the "data" attribute
In jQuery Tabs UI, I'm using this function (thanks to SO'ers) to change the CSS of a div in order to show a particular image according to the data-image attribute of the active tab.
Function:
var img = $(ui.panel).data("image");
$("#headerwrapper")
.animate({ opacity: 'toggle' }, function() {
$(this).css("background-image", "url(" + img + ")")
.animate({ opacity: 'toggle' });
});
}
HTML and CSS:
html in the tabs structure:
<div id="home" data-image="/images/water.jpg">tab content</div
<div id="about" data-image="/images/office.jpg">tab content</div>
...more tabs...
css (water.jpg is default when no data-image is present):
#headerwrapper {background: url(images/water.jpg);}
So I can correctly credit the photographer when their image is shown: how would I change that function (see below开发者_JS百科) in order to use a corresponding data attribute called credit to change the text of with the active tab? And can one have two different data attributes in the html? Or is there a better way?
Function:
var img = $(ui.panel).data("credit");
$("#headerwrapper")
.animate({ opacity: 'toggle' }, function() {
$(this).css("background-image", "url(" + img + ")") //what goes here in order
//change data-credit
//in the div photocredit?
.animate({ opacity: 'toggle' });
});
}
HTML: in the tabs structure:
<div id="home" data-image="/images/water.jpg" data-credit="Photog1">tab content</div
<div id="about" data-image="/images/office.jpg" data-credit="Photog2">tab content</div>
...more tabs...
In the site footer (outside of #headerwrapper) :
<div id="photocredit"></div>
And, what is the CSS for #photocredit? Just this: #photocredit {}
Use the attr
function to change the attribute of div
tag:
$(this).attr("data-credit", "Photographer...");
Here's one way to set the photocredit
Example Here: http://jsfiddle.net/pxfunc/VhvvG/
modified jQuery:
var $home = $('#home');
$('#headerwrapper').animate({
opacity: 'toggle'
}, function () {
$(this).css("background-image", "url(" + $home.data('image') + ")").animate({
opacity: 'toggle'
}).children('#photocredit').html($home.data('credit')); // set the photo credit from data-credit attribute to the child element #photocredit
});
I'm assuming the <div id="photocredit"></div>
is a child element of <div id="headerwrapper"...
element, if it isn't then do something like
$('#headerwrapper').animate({
opacity: 'toggle'
}, function () {
$(this).css("background-image", "url(" + $home.data('image') + ")").animate({
opacity: 'toggle'
})
});
$('#photocredit').html($home.data('credit')); // set the photo credit from data-credit attribute to the child element #photocredit
精彩评论