Javascript plus operator not works with ternary if else

痞子三分冷 提交于 2021-02-17 05:13:22

问题


Hi this is my js code.

var a = '<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1] ? $('#module_product_review_star_1 .pdp-link')[1].outerHTML : 'not have';
alert(a);

I'm using ternary operator to check the item exists in dom. But when the item is not in dom this code is failing.

this works,

if($('#module_product_review_star_1 .pdp-link')[1]){
         questiones = '<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1].outerHTML;
}

But I need to use ternary operator and do it in one line. Is there a way to do it?


回答1:


+ has higher operator precedence (13) than the conditional operator (4), so your code is checking whether '<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1] is truthy, which it always will be. Surround everything past the </span> in parentheses instead:

var a = '<span> and have </span>' + (
  $('#module_product_review_star_1 .pdp-link')[1]
    ? $('#module_product_review_star_1 .pdp-link')[1].outerHTML
    : 'not have'
);

That said, it would be better to write DRY code and put $('#module_product_review_star_1 .pdp-link')[1] into a variable first:

var possibleLink = $('#module_product_review_star_1 .pdp-link')[1];
var a = '<span> and have </span>' + (
  possibleLink
    ? possibleLink.outerHTML
    : 'not have'
);



回答2:


Ternary has this pattern:

condition ? do if true : do if false;


so in your case condition is

'<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1] 


来源:https://stackoverflow.com/questions/58519123/javascript-plus-operator-not-works-with-ternary-if-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!