我成功使用php implode fucnction来显示饮品类型。请参阅下面的代码。
<?php
echo 'Type:';
$types = array();
if ($a == 1) {$types[] = 'Pepsi';}
if ($b == 1) {$types[] = 'Mirinda';}
if ($c == 1) {$types[] = '7up';}
echo implode(', ', $types);
?>
现在我需要用jquery来做,即使用if语句创建数组,然后加入它们。你能帮我修改下面的代码来获得预期的结果吗?
$( "#view" ).html(
'<div>+
'Type:'+
(a == 1?"Pepsi, " :"") +
(b == 1?"Mirinda, " :"") +
(c == 1?"7up, " :"")+
'</div>');
我试过这种方式,但它不起作用:
$( "#view" ).html(
'<div>+
'Type:'+
(a == 1?types[] = 'Pepsi' :types[] = '') + //syntax error
(b == 1?types[] = 'Mirinda':types[] = '') + //syntax error
(c == 1?types[] = '7up' :types[] = '')+ //syntax error
types.join(',');
'</div>');
答案 0 :(得分:2)
说实话,我不知道你在那里做了什么,但是连接功能在没有所有东西的情况下都能正常工作。
var a = 1;
var b = 3;
var c = 1;
var types = [];
if (a == 1) types.push("Pepsi");
if (b == 1) types.push("Mirinda");
if (c == 1) types.push("7up");
$( "#view" ).html("Types: " + types.join(', '));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="view"></div>
&#13;
答案 1 :(得分:1)
您的问题对我来说并不清楚,但如果您想使用.join()
方法,那么首先应该有一个如下所示的数组:
var a = b = c = 1, arr = [];
a = (a == 1) ? arr.push("Pepsi"):""; // push to array if true
b = (b == 1) ? arr.push("Coke"):""; // push to array if true
c = (c == 1) ? arr.push("7up"):""; // push to array if true
$('div').html('Types:'+ arr.join(', ')); // then join it here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>