当前位置 : 主页 > 网页制作 > JQuery >

在jQuery中,为什么$.clone(this)与$(this).clone()相同?

来源:互联网 收集:自由互联 发布时间:2021-06-15
我在 jQuery’s .clone() 的API调用中实际上犯了一个错误: 而不是使用http://jsfiddle.net/AXsB5/17/(你需要点击小提琴来使.clone()得到执行): $(".foo").click(function() { var el = $(this).clone(); el.css({ col
我在 jQuery’s .clone()的API调用中实际上犯了一个错误:

而不是使用http://jsfiddle.net/AXsB5/17/(你需要点击小提琴来使.clone()得到执行):

$(".foo").click(function() {
    var el = $(this).clone();

    el.css({ color: "orange" });
    $("#bar").append(el);
});

我错误地使用了http://jsfiddle.net/AXsB5/18/:

$(".foo").click(function() {
    var el = $.clone(this);

    $(el).css({ color: "orange" });
    $("#bar").append(el);
});

jQuery API docs表明它不适用于第二种情况.我想知道为什么两种情况都有效

根据 $vs $():

Until now, we’ve been dealing entirely with methods that are called on
a jQuery object.

For example:

$( "h1" ).remove();

Most jQuery methods are called on jQuery objects as shown above; these methods are said to be part of the $.fn namespace, or the “jQuery prototype,” and are best thought of as jQuery object methods.

However, there are several methods that do not act on a selection; these methods are said to be part of the jQuery namespace, and are best thought of as core jQuery methods.

This distinction can be incredibly confusing to new jQuery users.
Here’s what you need to remember:

  • Methods called on jQuery selections are in the $.fn namespace, and automatically receive and return the selection as this.

  • Methods in the $namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments, and their return value will vary.

但是,使用调试器运行JSFiddle,似乎它甚至从未到达$.fn命名空间的clone()方法,实际上是命中$().clone().这可能是因为它在$.clone()(在加载jquery文件时运行)中映射了$().clone(),就像在Arun P Johny上面链接的源代码中一样.我希望这是有道理的……我的建议只是通过一个调试器来完成.

网友评论