我有一个简单的 ajax 请求返回一些数据,然后插入到模板文字中。我想知道是否可以在模板中插入“if”语句?
本质上是如果 json 对象有第五种颜色,则添加另一行代码。
$.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>`
)
})
})
您需要将逻辑移至函数中或使用三元运算符:
`${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>`
: ''}`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)