这个 jQuery 在做什么?
我称自己为中级 jQuery 开发人员,但我对这一行(来自 Twitter 的 Bootstrap)的作用感到困惑:
$tip.find('.help-popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)
具体来说,是方括号之间的部分。有人可以向我解释一下吗?
I would call myself an intermediate jQuery developer, but I'm confused about what this line (from Twitter's Bootstrap) is doing:
$tip.find('.help-popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)
Specifically, the part between the square brackets. Can anybody explain it to me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
内部语句使用三元运算符。它基本上是单行
if..else
语句,由于所选方法位于括号内,因此您可以使用字符串来选择方法
它等于:
The inner statement uses a ternary operator. It's basically a single line
if..else
statementSince the selected method is inside the brackets, you can use a string to select a method
It's equalvelent to:
它是一个内联 if 语句,也称为三元运算符。基本上,如果标题类型是“object”,那么它将获取索引“append”,否则获取索引“html”。希望这就是您问题的意思。
It's an inline if statement, otherwise called a ternary operator. Basically, if the type of title is 'object' then it's getting the index 'append', otherwise the index 'html'. Hope this what you meant by your question.
这里的重要概念是,对象属性不仅可以按字面直接访问,还可以使用包含带有属性名称的字符串(文字或变量)的方括号来访问。此外,函数始终是对象的属性——即使只是全局上下文。
首先,检查基于值的属性:
然后请注意,当属性值是函数时,它不会改变任何内容。它们仍然以相同的方式访问:
因此最终,您发布的代码片段只是检查
title
变量的类型并选择适当的函数以使其成为找到的元素的子元素。如果title
是一个对象,则附加它
。如果不是(它必须是文本),则使用html
函数代替。以这种方式编码是为了节省重复代码或声明新变量。三元运算符是正常过程
if
语句的表达形式(也就是说,它们计算某些内容而不是控制流程)。下面的示例将说明这一点:VB 的
Iif()
函数和 Excel 的IF()
工作表函数完全相同。The big concept here is that object properties can be accessed not just literally and directly but also with square brackets containing a String (literal or variable) with the name of the property. Also, functions are always properties of an object—even if only the global context.
First, check out value-based properties:
Then note that when the property values are functions it doesn't change anything. They are still accessed the same way:
So ultimately, the code fragment you posted is just checking the type of the
title
variable and choosing the appropriate function to make it a child of the found element. If thetitle
is an object,append it
. If it's not (it must be text) then use thehtml
function instead. It was coded this way to save duplicating code or declaring a new variable.Ternary operators are the expressive forms of normal procedural
if
statements (that is, they evaluate to something rather than controlling flow). The following example will show this:VB's
Iif()
function and Excel'sIF()
worksheet function are exactly equivalent.