我有一系列,我称之为堆栈的东西,里面有一个h1,h2和一些段落文本。这些元素中的每一个都使用一个数据样式属性,该属性以字体族名称作为值。
例如:
<h1 data-style="arial">Heading 1</h1>我想使用jQuery来获取堆栈中元素的值,在堆栈中悬停时,每个堆栈将显示在该特定堆栈上使用的字体。然后,一旦我得到了信息,就把它放在一个信息面板中供用户查看。
也许我在这个问题上走了很长的路,我对改进我的工作方式持开放态度。然而,我现在主要是迷路了,是时候寻求一些帮助了。
*增加了一个弹琴,以防有人想玩:http://jsfiddle.net/62rG4/2/
我的HTML:
<div id="font-info">
<h4>The follow fonts are used in this stack:</h4>
<p class="h1">h1:</p>
<p class="h2">h2:</p>
<p class="body">body:</p>
</div>
<div class="stack-1">
<h1 data-style="myfont">Heading 1</h1>
<h2 data-style="myfont">Heading two here</h2>
<p data-style="myfont">Hello world!</p>
</div>
<div class="stack-2">
<h1 data-style="myfont">Heading 1</h1>
<h2 data-style="myfont">Heading two here</h2>
<p data-style="myfont">Hello world!</p>
</div>jQuery (目前为止)
var fontInfo = null;
function letsGetThisFont(){
var fontInfo = $.map($("h1,h2,p").attr("data","style"), function (el, i) {
return $(el).text();
});
joined = fontInfo.join(" ");
return joined;
}
$(".stack-1").hover(function(){
console.log(letsGetThisFont());
});发布于 2014-02-25 02:18:20
几点
$.map()方法用于处理普通数组或对象。.map()处理包含DOM元素集合的jQuery对象$("h1,h2,p")选择器将选择文档中的所有元素,而不仅仅是悬停在上面的堆栈。您需要一种识别目标堆栈的方法。attr("data","style")方法将尝试将data属性的值设置为相等的样式。attr("data-style")获取data-style属性的值。尝尝这个
我试了一下。我不知道这是不是你想要的,但也许它能让你朝着正确的方向前进。
<div id="font-info">
<h4>The follow fonts are used in this stack:</h4>
<p class="h1">h1:</p>
<p class="h2">h2:</p>
<p class="body">body:</p>
</div>
<div class="stack">
<h1 data-style="myfont1">Heading 1 - Stack 1</h1>
<h2 data-style="myfont2">Heading two here - Stack 1</h2>
<p data-style="myfont3">Hello world! - Stack 1</p>
</div>
<div class="stack">
<h1 data-style="myfont6">Heading 1 - Stack 2</h1>
<h2 data-style="myfont5">Heading two here - Stack 2</h2>
<p data-style="myfont4">Hello world! - Stack 2</p>
</div>我稍微修改了HTML。为了测试目的,我更改了文本和data-style属性的值,这样我就可以看到我得到了正确的元素。我还删除了div类的唯一堆栈-*值。这样可以更容易地将悬停函数添加到所有堆栈中。如果需要唯一标识符,可以添加id属性。
CSS
我更改了这个CSS行:
div[class*="stack-"]{对此:
.stack {JavaScript
$(".stack").hover(function() {
var fonts = {};
$(this).find("h1,h2,p").each(function() {
var tag = $(this).prop("tagName").toLowerCase();
var font = $(this).attr("data-style");
fonts[tag] = font;
});
$("#font-info")
.find(".h1").text("h1: " + fonts.h1)
.end()
.find(".h2").text("h2: " + fonts.h2)
.end()
.find(".body").text("body: " + fonts.p);
});.map()和.each()都会给出相同的结果,但是我认为.each()的代码更加清晰,因为我们不需要生成新的jQuery对象。
这将适用于任何数量的div与class="stack"。它将获得包含在悬浮div中的最后一个data-style元素、最后一个h2元素和最后一个p元素的值。
https://stackoverflow.com/questions/21974496
复制相似问题