简体   繁体   English

在jQuery中内联if else语句

[英]inline if else statements in jQuery

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. 此函数构建的部分html取决于按下了哪个按钮。 I am using data- attributes to store my variables like this: 我使用数据属性来存储我的变量,如下所示:

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

And the html string I am building depends on what value the variable "div" is. 我正在构建的html字符串取决于变量“div”的值。 Is there a way to do an inline if/else statement in jQuery? 有没有办法在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! 谢谢!

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>

you can use condition ? code when true: code when false 你可以使用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. 但我建议你只坚持使用curley braces,因为它看起来更好,更容易调试。 one more thing , do it as below 还有一件事,如下所示

if(div==="choice1"){

}
else{
}

use === 使用===

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 + '">';

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM