jQuery 方法追加 : why is the position of the function relevant in the case of multiple parameters?

标签 jquery append

甚至没有记录( http://api.jquery.com/append/ ),但该方法的多个参数之一也有可能是一个函数:

$("#append1").click(function(){
  $("#list1").append(function(){
      return "<li>new</li>";
      },
    "<li>new</li>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="list1">
 <li>old</li>
</ol>
<button id="append1">append1</button>

在没有文档的情况下,任何人都可以向我解释为什么该脚本仅在函数参数是 jquery 追加方法参数的第一个参数时才有效,即: .append(function, content)?如果参数的顺序不同(即:内容,函数),该方法不起作用:

$("#append2").click(function(){
  $("#list2").append("<li>new</li>", function(){
      return "<li>new</li>";
      });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="list2">
 <li>old</li>
</ol>
<button id="append2">append2</button>

我认为这个问题不仅仅涉及jquery追加方法。

最佳答案

在jQuery源代码中,我发现arg[0]append调用的domManip中进行了特殊处理。 所以这是一个硬编码的行为。

追加

https://github.com/jquery/jquery/blob/821bf34353a6baf97f7944379a6459afb16badae/src/manipulation.js#L340-L347

append: function() {
    return domManip( this, arguments, function( elem ) {
        // ...
    } );
},

domManip

https://github.com/jquery/jquery/blob/821bf34353a6baf97f7944379a6459afb16badae/src/manipulation.js#L135-L136

function domManip( collection, args, callback, ignored ) {
    // ...
        value = args[ 0 ],
        valueIsFunction = isFunction( value );
    // ...
            if ( valueIsFunction ) {
                args[ 0 ] = value.call( this, index, self.html() );
            }
}

关于jQuery 方法追加 : why is the position of the function relevant in the case of multiple parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50317453/

相关文章:

jquery - 覆盖 jQuery 插件方法,默认情况下和单个实例

javascript - 无法在 'appendChild' : parameter 1 is not of type 'Node' error on append tr to a table 上执行 'Node'

javascript - 如何使用 Glimpse 找出导致 ASP.NET MVC 应用程序挂起的原因?

jquery/css 访问下面 HTML 中的以下 anchor 标记

python追加字典到列表

python - 如何 append 到文件?

jQuery append 对添加元素的引用

element.append 中的 JavaScript 变量值

javascript - 多次调用函数与使用 livequery

jquery - 为什么多个 JQuery 函数不能从代码隐藏中调用