在ES6模板文字中插入if语句 [英] Inserting if statement inside ES6 template literal

查看:46
本文介绍了在ES6模板文字中插入if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的ajax请求,它返回一些数据,然后插入模板文字中.我想知道是否可以在模板中插入"if"语句?

I have a simple ajax request returning some data and then inserting into a template literal. I was wondering if it it possible to insert an 'if' statement inside the template?

如果json对象具有第5种颜色,则基本上可以添加另一行代码.

Essentially to add a further line of code, if the json object has a 5th color.

  $.ajax({
url: 'http://localhost:8888/ColourCatchr%202/app/search.php'
}).done(function(results){
var res = jQuery.parseJSON(results);
console.log(res);
$.each(res,function(index,result){
  $('.palettes').append(`
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">${result.name}</h3>
      </div>
      <div class="panel-body">
        <div class="col-md-12 colors">
          <div class="color" style=background-color:#${result['color 1']}><h6>${result['color 1']}</h6></div>
          <div class="color" style=background-color:#${result['color 2']}><h6>${result['color 2']}</h6></div>
          <div class="color" style=background-color:#${result['color 3']}><h6>${result['color 3']}</h6></div>
          <div class="color" style=background-color:#${result['color 4']}><h6>${result['color 4']}</h6></div>

          ${if(result['color 5']){
            <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>
            }
          }

          <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>
          <p>on hover change to translucent background and black text for ecah color</p>
        </div>
      </div>
      <div class="panel-footer">
          <a class="btn btn-info btn-lg" href="update.html?id=${result.id}">Edit</a>
          <a class="btn btn-danger btn-lg">Delete</a>
      </div>
    </div>`
    )
})

})

推荐答案

您需要将逻辑移至函数中或使用三元运算符:

You'll need to move your logic into a function or use the ternary operator:

`${result['color 5'] ? 'color 5 exists!' : 'color 5 does not exist!'}`

基于评论的其他示例:

`${result['color 5'] ? 
    `<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>` 
: ''}`

这篇关于在ES6模板文字中插入if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆