Assign stored title attributes from one array to elements stored in another. jquery
I have twelve <span>
's with the class "has_title". Each has a unique title
.
I also have twelve <div>
's with the class "bar".
I need to assign the titles from the <span>
's in the order that they appear in the html to the <div>
's in the order that they appear in the html.
My idea was to use .each
to store the titles in an array and then somehow loop through开发者_如何学Go the array applying the titles to each of the <div>
's in turn
So far I have the following code which stores the values of the titles in an array:
var myarr = [];
$(".has_title").each(function(){
myarr.push({ title: this.title});
});
And the following that loops through the array:
$.each(myarr, function() {
// What goes here?
});
That's where I get stuck though. Am I even going about this in the right way? A little help would be great as I am about to throw my laptop through the window.
Try something like this:
var myarr = [];
$(".has_title").each(function(){
myarr.push({ title: this.title});
});
$(".bar").each( function(index) {
$(this).attr('title', myarr[index].title);
});
You would do something like this:
var titles = [];
$('.has_title').each(function()
{
titles.push(this.title);
});
$(titles).each(function(index)
{
$('.bar:eq(' + index + ')').title = this;
});
Should do the trick. Basically, use the callback which takes the index of the set, and then use the :eq()
selector to find the div in the set of that index and assign the title.
精彩评论