0

我有一张这样的桌子:

<table><tbody id="foo">
  <tr id="1"><td>a</td><td>b</td></tr>
  <tr id="2"><td>c</td><td>d</td></tr>
  <tr id="3"><td>e</td><td>f</td></tr>
</tbody></table>

当我应用 jQuery 操作时:

$('#foo').append($('#1'),$('#2'));

然后我得到以下(预期的)结果:

+-+-+
|e|f|
+-+-+
|a|b|
+-+-+
|c|d|
+-+-+

我想将该append()函数嵌入另一个函数myAppend()中,我这样做了:

$.fn.myAppend = function(s){
  this.append(s);
  // something to be, which is irrelevant to this question
};
$('#foo').myAppend($('#1'),$('#2'));

结果与上面不同,我得到了这个(无意):

+-+-+
|c|d|
+-+-+
|e|f|
+-+-+
|a|b|
+-+-+

为什么结果不一样?我怎样才能myAppend()以与 相同的方式进行工作append()

4

3 回答 3

1

您没有将第二个参数传递给append. 用于Function.prototype.apply调用append具有可变数量的方法arguments。为了能够链接方法调用,请this从方法内返回。

$.fn.myAppend = function() {
  return this.append.apply(this, arguments);
}

JS Bin 演示

于 2013-11-11T07:51:21.553 回答
0

是不是你需要传递两个参数,即和$('#1')函数..$('#2')myAppend

默认情况下,函数采用第一个参数,即$('#1')仅附加它。

或者您需要为要附加的每个项目使用循环

于 2013-11-11T07:50:38.333 回答
0

好吧,您在函数参数中传递了两个选择器,但您在那里使用了一个,因此您可以尝试在自定义myAppend函数中将其作为数组传递:

$('#foo').myAppend([$('#1'),$('#2')]);

演示小提琴

于 2013-11-11T08:04:17.610 回答