【问题标题】:Select Div Title Text and Make Array With Jquery选择 Div 标题文本并使用 Jquery 创建数组
【发布时间】:2014-07-21 21:08:35
【问题描述】:

我正在尝试将所有 div 标题属性中的文本添加到数组中,但我似乎无法选择正确的内容。

我需要标题,因为它将包含我需要使用的字符串。

这里有三个不同标题的div

<div class = 'test' title='title1'>Hello</div>
<div class = 'test' title='title2'>goodbye</div>
<div class = 'test' title='title2'>goodbye</div>

到目前为止,这是我的 Jquery。

$(document).ready(function() {

$array = $('[title][title!=]').each(function(){
  $(this).attr("title").makeArray;})

 alert($array)

});

警报只是说 [Object object]

在我的示例中,我尝试选择创建一个包含 [Title1, Title2, Title3] 的数组。

谁能帮我做这件事?

************************************更新*********** *************************

感谢第一个完美的工作。对此,我真的非常感激。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:
    var array = $.map($('[title][title!=""]'), function(el) { return el.title });
    

    FIDDLE

    选择所有title属性不为空的元素,并将title映射到一个数组

    【讨论】:

      【解决方案2】:
      var theArray = []; // set an empty array to a variable outside of scope
      
      $('.test').each(function() { // loop through all the .test divs
          var theTitle = $(this).attr('title'); // selects the text of the title for the current .test element
          theArray.push(theTitle); // this adds the text of the current title to the array
      });
      
      console.log(theArray); // just to test and make sure it worked, remove once verify
      

      【讨论】:

        【解决方案3】:

        我建议:

        var titles = $('.test').map(function(){
            return this.title;
        }).get();
        

        参考资料:

        【讨论】:

          猜你喜欢
          • 2012-02-27
          • 2012-03-16
          • 1970-01-01
          • 2019-04-01
          • 1970-01-01
          • 2011-12-19
          • 2012-08-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多