jQuery 中的内联 if else 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15683352/
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-26 15:35:26  来源:igfitidea点击:

inline if else statements in jQuery

javascriptjquery

提问by SkyeBoniwell

I have a jQuery function that is executed by two different buttons.

我有一个由两个不同按钮执行的 jQuery 函数。

$("#btnSearch, #btnDirectorSearch").click(function () {

Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:

此函数构建的部分 html 取决于点击了哪个按钮。我正在使用数据属性来存储我的变量,如下所示:

var div = $(this).data("str");

And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?

我正在构建的 html 字符串取决于变量“div”是什么值。有没有办法在 jQuery 中执行内联 if/else 语句?

if div = "choice1" {
    html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';

} else {
    html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}

That seems cumbersome and I'm hoping there is a better jQuery way of doing this.

这看起来很麻烦,我希望有更好的 jQuery 方法来做到这一点。

Thanks!

谢谢!

回答by benams

you have a syntax error

你有一个语法错误

if div = "choice1" 

should be

应该

if (div == "choice1")

Anyway, the pattern you're looking for is:

无论如何,您正在寻找的模式是:

div == "choice1" ? <code for true> : <code for false>

回答by Manish Mishra

you can use condition ? code when true: code when false

您可以使用 condition ? code when true: code when false

but i would suggest you to stick with curley braces only, as it looks better and easier to debug. one more thing , do it as below

但我建议你只坚持使用大括号,因为它看起来更好,更容易调试。还有一件事,按照下面的方法做

if(div==="choice1"){

}
else{
}

use ===

使用===

回答by Niet the Dark Absol

Since it's only the number that changes in the output, you could do this:

由于它只是输出中改变的数字,你可以这样做:

var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';

回答by Ja?ck

If your choices are limited, you could add a small lookup array:

如果您的选择有限,您可以添加一个小的查找数组:

var choices = {
    choice1: {
        str: "str1",
        data: "dataItem1"
    },
    choice2: { ... }
};

html += '<tr data-str="' + choices[div].str 
    + '" data-dataItem="' + choices[div].data
    + '" data-result-title="' + name + ... etc;