【问题标题】:jQuery text from span to title从跨度到标题的 jQuery 文本
【发布时间】:2013-01-11 15:42:20
【问题描述】:

我是一个 jQuery 新手。 我有类似下面的 HTML:

<div class=dcsns-youtube>
    <span class="section-thumb">
        <a href="some-link"><img src="http://img.youtube.com/vi/m4-1FZeoBtQ/default.jpg" alt=""></a>
    </span>
    <span class="section-title">
        <a href="some-link">Text on the link</a>
    </span>
<div>

我想使用类“section-title”获取跨度内a元素内的文本,在示例“链接上的文本”中,将其用作跨度内a元素的标题“section-thumb”类。

以下 jQuery 代码仅适用于单个 div:

jQuery('.dcsns-youtube .section-thumb a').attr('title', $('.dcsns-youtube .section-title').text());

如果我有多个 div,我如何才能完成这项工作?

【问题讨论】:

  • 您的最后一个问题不清楚。您的示例 HTML 中没有 div。
  • @crush 你什么意思。这个问题有div。

标签: jquery attr


【解决方案1】:

你可以这样做:

$('.dcsns-youtube').each(function(){
  $('.section-thumb a', this).attr('title', $('.section-title', this).text());
});

$(someselector, this) 搜索 this 内的元素。

Demonstration

您也可以将回调传递给attr

$('.dcsns-youtube .section-thumb a').attr('title', function(){
      return $(this).closest('.dcsns-youtube').find('.section-title a').text();
});

Demonstration

【讨论】:

  • 示例 HTML 中没有 DIV 元素!?
【解决方案2】:

您需要使用 jQuery each() 来访问所有给定的选择器元素。 each() 遍历选择器返回的集合,每个正文中的$(this) 给出集合中的html element 的jQuery 对象。

jQuery('.dcsns-youtube .section-thumb a').each(function(){        
     $(this).attr('title', $(this).closest('.section-title').text());    
});

【讨论】:

    【解决方案3】:

    我想使用类“section-title”获取跨度内a元素内的文本,在示例“链接上的文本”中,将其用作跨度内a元素的标题“section-thumb”类。

    这是用这个 jQuery 完成的:

    var text = $('span.section-title a').text();
    
    $('span.section-thumb').attr('title', text);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多