Javascript 这个函数中的问号是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7023317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:18:03  来源:igfitidea点击:

What does the question mark mean in this function?

javascriptjquery

提问by user784637

Here's the documentation for this plugin (There's only two functions.) http://tkyk.github.com/jquery-history-plugin/#documentation

这是这个插件的文档(只有两个功能。) http://tkyk.github.com/jquery-history-plugin/#documentation

$(document).ready(function() {
    function load(num) {
        $('#content').load(num +".html");
    }

    $.history.init(function(url) {
        load(url == "" ? "1" : url);
    });

    $('#ajax-links a').live('click', function(e) {
        var url = $(this).attr('href');
        url = url.replace(/^.*#/, '');
        $.history.load(url);
        return false;
    });
});

Here's the html:

这是html:

<body>
  <h1>jQuery History Plugin Ajax Sample</h1>
  <div id="ajax-links">
    <ul>
      <li><a href="#1">load 1.html</a></li>
      <li><a href="#2">load 2.html</a></li>
      <li><a href="#3">load 3.html</a></li>
    </ul>
    <div id="content"></div>
    <hr />
  </div>
  <p>[<a href="../">All samples</a>] [<a href="http://github.com/tkyk/jquery-history-plugin">Project home</a>]</p>
</body>

回答by foxy

load(url == "" ? "1" : url);

The question mark here is a a ternary if operation, Simply put, it is a short, inline ifstatement.

这里的问号是一个三元的 if 操作,简单来说就是一个简短的内联if语句

Expanded out, the statement would look something like this:

展开后,该语句将如下所示:

if (url == "")
    load("1");
else
    load(url);

If the statement before the question mark evaluates to true, then the left-hand side of the colon is used, otherwise (if it is false) the right-hand side is used. You can also nest this, though it isn't always a good idea (for readability).

如果问号前的语句求值为真,则使用冒号的左侧,否则(如果为假)使用冒号的右侧。您也可以嵌套它,尽管它并不总是一个好主意(为了可读性)。

回答by Curt

Its shorthand for:

它的简写:

If (url == ""){
   load("1");
}
else {
   load(url);
}

Ie. If urlequals ""then return "1", otherwise, return url

IE。如果url等于""则返回"1",否则返回url

In your example, if the urlequals ""then, 1.htmlwill be loaded, otherwise, url + ".html"will be loaded

在你的榜样,如果url等号""的话,1.html将被加载,否则,url + ".html"将被载入

回答by Sjoerd

It is a ternary operation.

这是一个三元运算