用多个框替换文本 [英] Replace text with multiple boxes
问题描述
我从jQuery开始,我需要一个项目.
I'm starting with jQuery and I need this is a project.
例如,我有这个:
<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>
网格项目的信息
<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>
还有一个div:
<div id="promo">I want to set grid info here</div>
我想要完成的是,当我将鼠标悬停在一个框上时,促销div将内容替换为相应的info_box
What i want to accomplish is when I hover over a box, the promo div replaces the content with the corresponding info_box
因此,当我将鼠标悬停在box1上时,我想在促销div中添加box_info_1的内容
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!
数据元素是HTML5标准的一部分,所有现代浏览器中使用.此外,jQuery定义了一个简单的标准,可以通过 $ .data()函数读写数据属性一个>.下面的示例将CSS选择器存储在每个元素的数据元素中,然后在实现悬停处理程序时对其进行引用.
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.
首先,告诉每个盒子"将其分配给哪个box-info元素(我们将在data属性中使用CSS选择器),如下所示:
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>
然后使用以下JavaScript获取元素并替换promo的内容:
Then use the following JavaScript to get the element and replace the contents of promo:
$('.box').hover(function() {
$('#promo').text($($(this).data('item')).text());
});
这篇关于用多个框替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!