【问题标题】:Object doesn't support property or method 'slice'对象不支持属性或方法“切片”
【发布时间】:2015-09-22 18:06:25
【问题描述】:

我是 Javascript/Jquery 世界的新手。 我有一个带有多个链接的 div,我想收集网址。

然后我想从那些href的最后9个字符中提取(实际上我希望优化它并独立收集每个字符串末尾的数字)。我尝试使用slice()方法提取它们但是它不工作。

在控制台中的错误是

对象不支持属性或方法“切片”

我可以将对象转换为字符串吗?感谢您的帮助! 代码如下

$(document).ready(function(){

  var $posts= $('a.entry_title').each(function(){
    $(this).attr('href');
  });

  var posts1 = $posts[0].slice(-9);
  var posts2 = $posts[1].slice(-9);

  var posts = ["MyURL"+ posts1,"MyURL"+posts2]
  $('#div1').load(posts[0] + " .shadow3");
  $('#div2').load(posts[1] + " .shadow3");

});
</script>

【问题讨论】:

    标签: javascript jquery slice


    【解决方案1】:

    您看到 Object 不支持,因为 $.each 返回一个 jQuery 对象。

    改用.map(),因为它返回一个数组,切片可以在该数组上工作

    var $posts= $('a.entry_title').map(function(){
       return $(this).attr('href');
    });
    

    结果是

    ["link1", "link2", "link3"....] // just a sample
    

    如果你想得到一个包含每个链接最后九个字符的 href 数组,你可以这样使用 map

    var $posts= $('a.entry_title').map(function(){
       return $(this).attr('href').slice(-9); // or you can do your own magic
    });
    

    结果如下所示

    ["k1", "k2", "k3"....] // after slicing the words 
    

    【讨论】:

      【解决方案2】:

      尝试下一个:

      var hrefs = []; // list of collected and sliced hrefs.
      var $posts= $('a.entry_title').each(function() {
          // slice & push each href into list.
          hrefs.push($(this).attr('href').slice(-9));
      });
      console.log('href list:', hrefs); // control result.
      var posts = ["MyURL"+ hrefs[0],"MyURL"+hrefs[1]]
      

      【讨论】:

        猜你喜欢
        • 2019-07-05
        • 2015-04-14
        • 2020-09-03
        • 2015-04-09
        • 2014-01-12
        • 2016-08-20
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多