Javascript plus operator not works with ternary if else

前端 未结 2 1627
感动是毒
感动是毒 2021-01-27 07:51

Hi this is my js code.

var a = \' and have \' + $(\'#module_product_review_star_1 .pdp-link\')[1] ? $(\'#module_product_review_star_1 .p         


        
相关标签:
2条回答
  • 2021-01-27 08:16

    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] 
    
    0 讨论(0)
  • 2021-01-27 08:39

    + 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'
    );
    
    0 讨论(0)
提交回复
热议问题