从$ .each

时间:2018-09-11 15:23:35

标签: javascript jquery

我有以下示例php代码,用于方法类型和此类文档-

 <?php 
    $arrTestData = [ 
                  1 => [
                     'id' => '1',
                     'name' => 'Written'
                  ],
                  2 => [
                    'id' => '2',
                    'name' => 'Verbal'
                  ]
    ];
    $arrDocuments = [ 
                   1=> [
                      'file_id' => '1',
                      'file_name' => 'TestDoc.pdf'
                   ],
                   2=> [
                       'file_id' => '2',
                       'file_name' => 'pranav.pdf'
                  ]
    ];
   $arrVariable = json_encode( $arrTestData );
  $arrDocuments = json_encode( $arrDocuments );?>

我将json_encode数据传递给了javascript。但是我想检查文档是否存在,然后仅在动态创建的行中显示文档下拉列表。也可以从第一个下拉菜单中跳过WRITTEN类型。 js代码看起来像-

$(document).ready(function () {
var response = '<?php echo $arrVariable; ?>';
var docs = '<?php echo $arrDocuments; ?>';
data = $.parseJSON(response);
doc = $.parseJSON(docs);

var counter = 1;
var newRow = $("<tbody>");
$('.addNotice').on('click',function() {
        var strHtml = "";
        strHtml += "<tr class=row" + counter + " bRow><td class=align-center border-right>" + counter + "</td>";
        strHtml += "<td><select class=form-select wide3 js-method name=violation_template_notices[" + counter + "][violation_warning_type_id] value=''>";
        $.each(data,function(key,value) {
            strHtml += "<option value="+ value.id +">"+ value.name +"</option>";
        });
        strHtml += "</select></td><td><select class=form-select wide3 js-method name=violation_template_notices[" + counter + "][document_id] value=''>";
        $.each(doc,function(key,value) {
            strHtml += "<option value="+ value.file_id +">"+ value.file_name +"</option>";
        });
        strHtml += "</select></td>";
        strHtml += "<td>--</td>";
        strHtml += "<td>--</td>";
        strHtml +="</tr>";
        counter++;
        newRow.append(strHtml);
        $("table").append(newRow);
    });
});

我尝试使用if(doc.length == 0){//隐藏下拉菜单},但第一次下拉菜单失败。

1 个答案:

答案 0 :(得分:0)

这将跳过doc json中的第一项。在(key !== index)处更改索引以选择要跳过的项目。

if (doc.length) {
    strHtml += "<select class=form-select wide3 js-method name=violation_template_notices[" + counter + "][document_id] value=''>";
    $.each(doc,function(key,value) {
          if (key !== 0) strHtml += "<option value="+ value.file_id +">"+ value.file_name +"</option>";
    });
    strHtml += "</select>";
} else {
    strHtml += "<select class=empty></select>";
}