I'm starting with jQuery and I need this is a project.
For example I have this:
<ul id="grid">
<li class="box1">Lorem ipsum dolor sit amet!</li>
<li class="box2">Lorem ipsum dolor sit amet!</li>
<li class="box3">Lorem ipsum dolor sit amet!</li>
</ul>
And Information for the grid items
<div class="box_info_1">Info for grid item</div>
<div class="box_info_2">Info for grid item</div>
<div class="box_info_3">Info for grid item</div>
And a div:
<div id="promo">开发者_StackOverflow社区;I want to set grid info here</div>
What i want to accomplish is when I hover over a box, the promo div replaces the content with the corresponding info_box
So when I hover over box1, i want the content of box_info_1 in the promo div
I love to use data element selectors, and so can you!
Data elements are part of the HTML5 standard, seen here, allowing a user to associate ad-hoc data with any element. They are available in all modern browsers. Further, jQuery defines a simple standard to read and write to data attributes through the $.data() function. The following example stores a CSS-selector in a data-element for each element, and then references it when implementing the hover handler.
First, tell each "box" which box-info element it is assigned to (we'll use a CSS-selector in a data attribute), as follow:
<ul id="grid">
<li class="box box1" data-item=".box_info_1">Lorem ipsum dolor sit amet!</li>
<li class="box box2" data-item=".box_info_2">Lorem ipsum dolor sit amet!</li>
<li class="box box3" data-item=".box_info_3">Lorem ipsum dolor sit amet!</li>
</ul>
Then use the following JavaScript to get the element and replace the contents of promo:
$('.box').hover(function() {
$('#promo').text($($(this).data('item')).text());
});
$('.box1').hover(function(){
$('#promo').text($('.box_info_1').text());
});
Or, for all the boxes
$('#grid li').hover(function(){
var currentNumber = $(this).attr('class').substr(3);
var currentText = $('.box_info_'+currentNumber).text();
$('#promo').text(currentText);
});
var txt = $('#promo').text();
$('#grid li').hover(function() {
var boxIndex = $('#grid li').index(this);
$('#promo').empty().text($('.box_info_' + (boxIndex + 1) + '').text());
},
function() {
$('#promo').empty().text(txt);
});
精彩评论