duanjiong5023 2015-01-18 14:45
浏览 42
已采纳

Jquery-使用if语句和连接数组元素创建数组

I successfully use php implode fucnction to display drink types. Please see below code.

<?php 
echo 'Type:';
$types = array();    
if ($a == 1) {$types[] = 'Pepsi';}
if ($b == 1) {$types[] = 'Mirinda';}  
if ($c == 1) {$types[] = '7up';} 
echo implode(', ', $types);
?>

Now I need to do that with jquery i.e. create array using if statements and then join them. Could you help me to modify the code below to get the expected result.

$( "#view" ).html(
   '<div>+
   'Type:'+
   (a == 1?"Pepsi, " :"") +
   (b == 1?"Mirinda, " :"") +    
   (c == 1?"7up, " :"")+
   '</div>');

I tried in this way but it did not work:

 $( "#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>');
  • 写回答

2条回答 默认 最新

  • dooso0594 2015-01-18 14:49
    关注

    To be honest I don't know what you're trying to do there, but the join function works without all the stuff around it.

    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(', '));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="view"></div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件