【问题标题】:Assign stored title attributes from one array to elements stored in another. jquery将存储的标题属性从一个数组分配给存储在另一个数组中的元素。 jQuery
【发布时间】:2011-09-07 21:49:06
【问题描述】:

我有 12 个 <span> 的“has_title”类。每个都有一个唯一的title

我还有 12 个 <div> 的类“bar”。

我需要将 <span> 中的标题按照它们在 html 中出现的顺序分配给 <div>,按照它们在 html 中出现的顺序它们

我的想法是使用.each 将标题存储在一个数组中,然后以某种方式循环遍历数组,依次将标题应用于每个<div>

到目前为止,我有以下代码将标题的值存储在一个数组中:

var myarr = [];
$(".has_title").each(function(){
    myarr.push({ title: this.title});
});

以及以下循环遍历数组的内容:

$.each(myarr, function() {
    // What goes here?
});

这就是我卡住的地方。我是否以正确的方式解决这个问题? 当我要把我的笔记本电脑扔出窗外时,一点帮助会很棒。

【问题讨论】:

    标签: jquery html arrays


    【解决方案1】:

    试试这样的:

    var myarr = [];
    $(".has_title").each(function(){
        myarr.push({ title: this.title});
    });
    
    $(".bar").each( function(index) {
        $(this).attr('title', myarr[index].title);
    });
    

    【讨论】:

    • +1 - 这个解决方案比我的更好。我不敢相信我没有想到这一点。
    • 谢谢马特。你是一个救生员!
    【解决方案2】:

    你会这样做:

     var titles = [];
     $('.has_title').each(function()
     {
         titles.push(this.title);
     });
    
     $(titles).each(function(index)
     {
         $('.bar:eq(' + index + ')').title = this;
     });
    

    应该做的伎俩。基本上,使用获取集合索引的回调,然后使用:eq() 选择器在该索引的集合中查找 div 并分配标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      相关资源
      最近更新 更多