简体   繁体   中英

inline if else statements in jQuery

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

$("#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:

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?

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.

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

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 ===

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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