質問

how can I convert the below code in ternary way?

if(epaper.othermakemodel.is(':checked')){
$("#dcolor").insertAfter("#lmodel");
}else{
$("#dcolor").insertBefore("#otherlabeldiv");
}
役に立ちましたか?

解決

This would work:

var c = epaper.othermakemodel.is(':checked');
$("#dcolor")["insert" + (c ? "After" : "Before")](c ? "#lmodel" : "#otherlabeldiv");

Or even a one-liner:

$("#dcolor")["insert" + (epaper.othermakemodel.is(':checked') ? "After" : "Before")](epaper.othermakemodel.is(':checked') ? "#lmodel" : "#otherlabeldiv");

However, that's just using the ternary operator for the sake of using the operator.

Keep your code short, but more importantly, keep your code readable:

var element = $("#dcolor");
if(epaper.othermakemodel.is(':checked')){
    element.insertAfter("#lmodel");
}else{
    element.insertBefore("#otherlabeldiv");
}

This will save everyone involved a headache if you have to maintain your code a year from now.

他のヒント

You can do this transformation when you only have one expression per line

condition ?     // if (condition)
    expr_true   //     expr_true;
:               // else
    expr_false; //     expr_false;

So yours would become

epaper.othermakemodel.is(':checked') ?
    $("#dcolor").insertAfter("#lmodel")
:
    $("#dcolor").insertBefore("#otherlabeldiv");

It's not really helpful in your case, though.

Remember, the majority of whitespace has no meaning in JavaScript, so you could even write this on one line with if..else.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top