我正在为带有缩略图的图片库编写一个 jQuery 函数。网页顶部有一个 div,它将显示点击缩略图的放大版本以及标题和说明。
单击缩略图时,标题如我所料更改,但描述保持默认(由 HTML 定义)。
缩略图在无序列表中,如下所示:
<ul class=thumblist id=thumblist>
<li><a title="thumb1" description="this is the first pic"></a></li>
<li><a title="thumb2" description="this is the second pic"></a></li>
</ul>
这是 jQuery 函数:
$('.thumblist a').click(function() {
$("#title").text(this.title);
$("#description").text(this.description);
});
我该怎么做才能修复我的标记并实现我正在寻找的功能?
最佳答案
你想要 attr
function :
$('.thumblist a').click(function() {
var $this = $(this);
$("#title").text($this.attr("title")); // Or `this.title`, see below
$("#description").text($this.attr("description"));
});
它半途而废的原因是 title
是一个有效的 HTML 属性,它有一个 reflected property在 DOM 元素实例上,所以 this.title
给了你那个属性;但是 description
不是,所以没有反射(reflect) description
属性。使用 attr
去寻找实际的属性值。
理想情况下,使用 data-*
attributes用于未由任何标准定义的临时属性(如您的描述
)。
关于jquery - 如何使用一个 jQuery 函数更改两个独立元素内的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13869918/