0

嗨,这是我的 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

2 回答 2

3

+具有比条件运算符 (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'
);
于 2019-10-23T09:01:55.843 回答
1

三元有这种模式:

condition ? do if true : do if false;


所以你的情况是

'<span> and have </span>' + $('#module_product_review_star_1 .pdp-link')[1] 
于 2019-10-23T09:02:06.817 回答