【问题标题】:How does one change the text inside of two separate elements using one jQuery function?如何使用一个 jQuery 函数更改两个独立元素内的文本?
【发布时间】:2012-12-13 22:50:31
【问题描述】:

我正在为带有缩略图的图片库编写一个 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);         
  }); 

我可以做些什么来修复我的标记并实现我正在寻找的功能?

【问题讨论】:

  • 请出示显示大图的代码。

标签: jquery html web-applications jquery-selectors functional-programming


【解决方案1】:

你想要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 属性,在 DOM 元素实例上有一个 reflected property,所以 this.title 给了你这个属性;但description 不是,所以没有反映description 属性。使用attr 查找实际的属性值。

理想情况下,将data-* attributes 用于未由任何标准定义的临时属性(如您的description)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多