jQuery/Javascript语法

4
我正在尝试弄清楚下面的语法是做什么的。这是来自Bootstrap气泡窗口的代码。
//title is a string
$tip.find('.popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)
                           ^                                                 ^
                       What does this symbol mean?                    Whats happening here?

@pimvdb 在早期版本的jQuery中也是这样吗? - Naftali
3个回答

6

让我们来拆分一下:

$tip.find('.popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)

这可以分解为以下内容:

var found = $tip.find('.popover-title');
found[$.type(title) == 'object' ? 'append' : 'html'](title);

更多内容:

var found = $tip.find('.popover-title');

if ($.type(title) == 'object') {
  found['append'](title);
} else {
  found['html'](title);
}

一点更多:
var found = $tip.find('.popover-title');

if ($.type(title) == 'object') {
  found.append(title);
} else {
  found.html(title);
}

1
啊哈,Blendy。你就是要比我更出色 :-P - Naftali
这并不是100%正确的。你失去了在func赋值中对found隐式this值的引用。 - pimvdb
@pimvdb:你是什么意思?我并没有在代码中真正看到“this”被使用。 - Blender
1
@Blender:在你的代码中,如果 func === $.fn.append 或者 func === $.fn.html,为了在元素上使用它(正确设置 this 值),你需要执行 func.call(found, title)。只有当你执行 foo.append() 时,this 值才会自动设置为 foo - pimvdb

5
基本上它的意思是:
if(typeof title == 'object') {
    $tip.find('.popover-title').append(title);
}
else {
    $tip.find('.popover-title').html(title);
}
< p > [...] 表示您可以从 $tip.find('.popover-title') 对象中动态选择函数。


这里,给你一些补偿 ;) $.type() 除了将 typeof 包装在函数中之外,实际上还有其他作用吗?我真的不明白为什么你需要在这段代码中使用 $.type()... - Blender
@Blender 哈哈,所以我使用了 typeof。jQuery 喜欢为已经存在的东西创造新的函数 :-P - Naftali
@Blender 尽管它似乎可能具有更多功能来检测更多的事情。http://api.jquery.com/jQuery.type/ - Naftali

2

$("selector")["append"](...) 等同于 $("selector").append(...)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接