2017-01-03 139 views
0

jQuery的.append()函数可以接受多个参数,无论是平面还是数组。我有一些代码,我需要追加3个项目,其中一个可能不存在,如:有没有办法将'missing'对象传递给.append()

whatever.append(always).append(maybe).append(alwaysToo); 
/* or */ 
whatever.append(always, maybe, alwaysToo); 
/* or */ 
var arrayOfThoseThree = [ always, maybe, alwaysToo ]; 
whatever.append(arrayOfThoseThree); 

我不能从jQuery的文档是些什么东西,如果有的话,的maybe值应说“忽略这一个”:

maybe = ''; 
maybe = null; 
maybe = undefined; 
maybe = ??? 

为:

maybe = needMaybe ? $('<blah...>') : ignoreThisValue; 

我可以,当然,做这样的事情:

whatever.append(always); 
if (maybe) whatever.append(maybe); 
whatever.append(alwaysToo); 

但是这难看(尤其是因为这是一个较大的链的一部分)。

我可以尝试不同的值,直到找到一个“工作”,但我希望有一个“官方”记录的方式,不会失败未来一天的工作,因为我使用的是“无证的功能“。

指向正确的方向吗?

[编辑]

我想一般,但在我面前的具体的例子是:

var titl = this.dataset.title;    /* optional */ 
var ifr = $('<iframe>'); 
var bas = $('<base href="' + document.baseURI + '">'); 
var ttl = titl ? $('<title>' + titl + '</title>') : null; /* HERE */ 
var lnk = $('<link rel="stylesheet" href="/css/print.css">'); 
/* ... */ 
ifr.contents().find('head').append(bas, ttl, lnk); 
+2

如果你测试它,会发生什么? – Mouser

+0

我们能否看到更多的逻辑?为什么变量会保持一个空/空值? –

+1

测试可能会找到一种“有效”的方式,但它不会告诉我是否有支持的方式在未来不会神秘破坏。 –

回答

3

如何

whatever.append([always, maybe, alwaysToo].filter(item => !!item)); 
+0

这看起来很有前途。 –

1

这里是在发生了什么jQuery代码(我正在使用的版本)。 请注意,这定义了什么“”今天工作“,而不是什么被记录工作,并继续在未来工作。

.append()功能同样写到许多人在domManip()做许多工作:

append: function() { 
     return this.domManip(arguments, function(elem) { 
       if (this.nodeType === 1 || 
        this.nodeType === 11 || 
        this.nodeType === 9) { 
         var target = manipulationTarget(this, elem); 
         target.appendChild(elem); 
       } 
     }); 
}, 

的第一件事情domManip()所做的是:

domManip: function(args, callback) { 
     // Flatten any nested arrays 
     args = concat.apply([], args); 

然后调用buildFragment()

 fragment = jQuery.buildFragment(args, ...); 

其作用:

buildFragment: function(elems, context, scripts, selection) { 
     var /* ..., */ i = 0; 
     for (; i < l; i++) { 
       elem = elems[ i ]; 
       if (elem || elem === 0) { 
         /* ... process this argument ... */ 
       } 
     } 

所以空数组得到由Array.prototype.concat()然后任何测试失败(elem || elem === 0)被忽略压扁。

所以,其实,当ttl可能是null,所有这些(目前)做 “正确的事情”:

whatever.append(bas, ttl, lnk); 
whatever.append([bas, ttl, lnk]); 
whatever.append([bas],[ttl], [lnk]); 
whatever.append(bas, [ttl], lnk); 

whatever.append(bas).append(ttl).append(lnk); 
whatever.append(bas).append([ttl]).append(lnk); 

但是,尽可能接近我能找到,该文档没有声明可以使用的值或值,这些值将被安全地忽略(现在和永远)。

因此最安全的操作过程中(至少在=>支持)是从阿尔舍了答案:

whatever.append([bas, ttl, lnk].filter(e => !!e)); 
相关问题