关于JQuery:如果var不为空,则在javascript中显示链接,检查var endefined不工作

Display a link in javascript if var is not empty. checking var endefined not working

本问题已经有最佳答案,请猛点这里访问。

只有当var不为空时,我才需要在sweetalk html中显示链接。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$('.patient-details').click(function(e) {
e.preventDefault();
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');
var address = $this.data('address');
var report = $this.data('report');
swal({
title: name,
html:
   "Gender:" + gender +"" +
  "Age:" + age +"" +
  "Country:" + country +"" +
  "Address:" + address +"" +
   (report!=undefined?'View Report':''),
});
});

我只需要在var报告不为空时显示报告链接。这是密码笔:https://codepen.io/pamela123/pen/gojzgo网站

我试过

1
2
3
if(report){
report = $this.data('report');
}

报告"未定义"。报告!=未定义不起作用。

但是如果报告为空,如何不在HTML中显示报告链接??

我知道这是一个简单的javascript问题,但是作为一个新手,我不能再进一步了。


将数据放入单独的变量中。

然后检查report是否不是undefined。如果没有,将其添加到变量中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$('.patient-details').click(function(e) {
  e.preventDefault();
  var $this = $(this)
  var name = $this.data('name');
  var gender = $this.data('gender');
  var age = $this.data('age');
  var country = $this.data('country');
  var address = $this.data('address');
  var report = $this.data('report');

  var htmlData ="Gender:" + gender +"" +
     "Age:" + age +"" +
     "Country:" + country +"" +
     "Address:" + address +"";
  if( report !== undefined && report !="" ) {
    htmlData +=  'View Report'
  }
  swal({
    title: name,
    html: htmlData
  });
});


您可以如下更新您的代码

1
2
3
4
5
6
7
8
var htmlTemplate="Gender:" + gender +"" +"Age:" + age +"" +"Country:" + country +"" +"Address:" + address +"" ;
if(report){
   htmlTemplate+= 'View Report';
}
swal({
title: name,
html: htmlTemplate,
});


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$('.patient-details').click(function(e) {
e.preventDefault();
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');
var address = $this.data('address');
var report = $this.data('report');
swal({
title: name,
html:
   "Gender:" + gender +"" +
  "Age:" + age +"" +
  "Country:" + country +"" +
  "Address:" + address +"" +(typeof report !=="undefined" && report !=""?'View Report':'')
    ,
});
});