jquery - 如何使用一个 jQuery 函数更改两个独立元素内的文本?

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

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

相关文章:

javascript - focusin 事件中的alert() 继续弹出

javascript - SumoSelect 重新加载后无法打开

html - 在表中使用固定填充和百分比宽度

php - 由 Jquery (AJAX) 在服务器的 PHP 代码中发送的调试变量

java - jetty LdapLoginModule : Login Failure: all modules ignored

c# - 无法使用 json 和 ajax 调用从 webservice 方法获得响应

javascript - 移动响应表单不起作用

html - 第一个和第二个 Bootstrap 表列之间的大空白

javascript - react : why the tasks doesn't appear?

web-applications - 网络应用程序与桌面应用程序的 future