我有一系列,我正在调用的堆栈 - 其中包含h1
,h2
和一些段落文本。这些元素中的每一个都使用具有字体系列名称作为值的数据样式属性。
例如:
<h1 data-style="arial">Heading 1</h1>
我想用jQuery做什么;在悬停堆栈时获取堆栈中元素的值 - 因此悬停每个堆栈将显示该特定堆栈上使用的字体。然后,一旦我获得了这些信息,就让它放在一个信息面板中供用户查看。
也许我正在走这条路的漫长路线,我愿意改善我的行为方式。然而,我现在主要迷失了,现在是时候寻求帮助了。
*添加一个jsfiddle,任何人都想要一个游戏: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());
});
答案 0 :(得分:0)
$.map()
方法用于处理普通数组或对象。
使用.map()
处理包含DOM元素集合的jQuery对象
$("h1,h2,p")
选择器将选择文档中的所有元素,而不仅仅是您悬停的堆栈。您需要一种方法来识别目标堆栈。
attr("data","style")
方法会尝试将data
属性的值设置为等于 style 。
使用attr("data-style")
获取data-style
属性的值。
<强> 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">
<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对象。
这适用于class="stack"
的任意数量的div。它将获取最后data-style
元素h1
属性的值以及悬停div中包含的最后h2
元素和最后p
元素。