繁体   English   中英

Javascript plus 运算符不适用于三进制 if else

[英]Javascript plus operator not works with ternary if else

嗨,这是我的 js 代码。

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);

我正在使用三元运算符来检查项目是否存在于 dom 中。 但是,当该项目不在 dom 中时,此代码将失败。

这有效,

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

但是我需要使用三元运算符并在一行中完成。 有没有办法做到这一点?

+具有比条件运算符 (4) 更高的运算符优先级 (13),因此您的代码正在检查'<span> and have </span>' + $('#module_product_review_star_1.pdp-link')[1]是否为真,它永远都是。 </span>之后的所有内容用括号括起来:

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'
);

也就是说,最好编写 DRY 代码并首先将$('#module_product_review_star_1.pdp-link')[1]放入变量中:

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

三元有这种模式:

condition ? do if true : do if false;


所以你的情况是

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

暂无
暂无

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

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