jQuery拆分和每个

时间:2016-05-20 04:51:24

标签: jquery split

我正在尝试从字符串创建面包屑,例如:

var str = 'home/files/';
var crumbs = [];
crumbs = str.split('/');
var nav;
$.each(breadcrumbsUrls, function(u, i) {
   if (i.length !== -1) {
      nav += '<a href="'+u+'"></a> ' + i + ' <span class="arrow">→</span> ';
    }
});

但我最终还是坚持:

undefinedhome → files → →

结果应该是:

home → files

2 个答案:

答案 0 :(得分:1)

试试这个:

var str = 'home/files/';
var crumbs = [];
crumbs = str.split('/');
crumbs = jQuery.grep(crumbs, function(n, i){ // remove all empty values from array using this
  return (n !== "" && n != null);
});
var nav = '';
$.each(crumbs, function(u, i) {
    if((crumbs.length-1) != u) { // if not last record - add arrow
        nav += '<a href="'+u+'"></a> ' + i + ' <span class="arrow">→</span> '; 
    } else {
        nav += '<a href="'+u+'"></a> ' + i;
    }
});

答案 1 :(得分:0)

var str = 'home/files/';
var crumbs = [];
crumbs = str.split('/');
var nav = ''; // changed
$.each(breadcrumbsUrls, function(u, i) {
  if (i.length >0 ) { // changed
   nav += '<a href="'+u+'"></a> ' + i + ' <span class="arrow">→</span> ';
  }
});