【问题标题】:Deciding the value in console log based on the column value根据列值确定控制台日志中的值
【发布时间】:2021-09-04 02:41:54
【问题描述】:

请看我下面的代码。我有一个YearEligible 列,每个记录的单元格中有YN 值。基于此,我想确定单击Get rows 按钮时Year 列发送什么值。

详细说明我的要求:

假设我检查了第一行(如下图所示):

当我单击Get rows 按钮时,我可以在console.log 中看到以下内容,看起来不错:

[{
  available: true,
  boundindex: 0,
  firstname: "Mayumi",
  lastname: "Nagase",
  price: 3.25,
  productname: "Espresso con Panna",
  quantity: 6,
  total: 19.5,
  uid: 0,
  uniqueid: "2128-24-28-17-311629",
  visibleindex: 0,
  yeareligible: "Y",
  yearValue: "2011"
}]

但是,假设我选择Year Eligible 列的值为N 的记录并单击Get rows 按钮,我会在console.log 中看到以下内容:

[{
  available: true,
  boundindex: 1,
  firstname: "Regina",
  lastname: "Davolio",
  price: 3.3,
  productname: "Doubleshot Espresso",
  quantity: 8,
  total: 26.4,
  uid: 1,
  uniqueid: "2917-25-23-18-212828",
  visibleindex: 1,
  yeareligible: "N"
}]

我的观察:

上面的console.log 没有为yearValue 返回任何东西,这是有道理的,因为我没有选择任何东西。

我的问题:

  1. 在上述情况下,是否可以将默认值 yearValue 作为 -1 返回?基本上,当用户选择Year Eligible 值设置为N 的记录时,我想将yearValue 包含为-1

  2. Year 列下Year Eligible 列的值为N 的单元格上显示不适用?

  var data = new Array();
  var firstNames = [
      "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"];
  var lastNames = [
      "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Bjorn", "Nodier"];
      var yearEligible = [
      "Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"];
  var productNames = [
      "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"];
  var priceValues = [
      "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"];
  for (var i = 0; i < 10; i++) {
      var row = {};
      var productindex = Math.floor(Math.random() * productNames.length);
      var price = parseFloat(priceValues[productindex]);
      var quantity = 1 + Math.round(Math.random() * 10);
      row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];
      row["lastname"] = lastNames[Math.floor(Math.random() * lastNames.length)];
      row["yeareligible"]= yearEligible[Math.floor(Math.random() * lastNames.length)];
      row["productname"] = productNames[productindex];
      row["available"] = !!(i % 2);
      row["price"] = price;
      row["quantity"] = quantity;
      row["total"] = price * quantity;
      data[i] = row;
  }
  var source = {
      localdata: data,
      datatype: "array"
  };
  var dataAdapter = new $.jqx.dataAdapter(source, {
      loadComplete: function (data) {},
      loadError: function (xhr, status, error) {}
  });
  $("#jqxgrid").jqxGrid({
      theme: 'energyblue',
      width: 500,
      autoheight: true,
      editable: true,
      source: dataAdapter,
      columns: [{
          text: 'Available',
          datafield: 'available',
          width: 100,
          columntype: 'checkbox'
      }, {
          text: 'First Name',
          datafield: 'firstname',
          width: 100
      }, {
          text: 'Last Name',
          datafield: 'lastname',
          width: 100
      }, {
          text: 'Year Eligible',
          datafield: 'yeareligible',
          width: 100
      },
       {
          text: 'Year',width: 120,datafield:'yearValue' , columntype: 'dropdownlist', editable: true,
          createeditor: function (row, column, editor) {
                    var list = ['2010', '2011', '2012' ,'2013','2014','2015','2016','2017','2018','2019','2020','2021'];
                  
                   
                     
                    editor.jqxDropDownList({ autoDropDownHeight: true, source: list, selectedIndex: 0 });
                }
       
      },
      {
          text: 'Product',
          datafield: 'productname',
          width: 180
      }, {
          text: 'Quantity',
          datafield: 'quantity',
          width: 80,
          cellsalign: 'right'
      }, {
          text: 'Unit Price',
          datafield: 'price',
          width: 90,
          cellsalign: 'right',
          cellsformat: 'c2'
      }, 
     
      
      {
          text: 'Total',
          datafield: 'total',
          width: 100,
          cellsalign: 'right',
          cellsformat: 'c2'
      }]
  });
  
   $('#jqxbutton').click(function () {
    var rows = $('#jqxgrid').jqxGrid('getrows');
  
     var selectedRows = rows.filter(x => x.available)
     
    console.log(selectedRows)
   
     //alert(rows);
 });
  
 
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet"/>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet"/>
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<div id="jqxgrid"></div>
<input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" />

已编辑:根据 Calculuswhiz 的回答测试 2016aggregate 的默认值:

let firstNames = [
  "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", 
  "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
];

let lastNames = [
  "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", 
  "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", 
  "Vileid", "Saylor", "Bjorn", "Nodier"
];

let yearEligible = [
  "Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"
];

let productNames = [
  "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", 
  "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", 
  "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
];

let priceValues = [
  "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
];

let data = [];
for (let i = 0; i < 10; i++) 
{
  let productindex = Math.floor(Math.random() * productNames.length);
  let price = parseFloat(priceValues[productindex]);
  let quantity = 1 + Math.round(Math.random() * 10);
  let row = {
    firstname : firstNames[Math.floor(Math.random() * firstNames.length)],
    lastname : lastNames[Math.floor(Math.random() * lastNames.length)],
    yeareligible : yearEligible[Math.floor(Math.random() * lastNames.length)],
    productname : productNames[productindex],
    available : !!(i % 2),
    price : price,
    quantity : quantity,
    total : price * quantity
  };
  data.push(row);
}

let source = {
  localdata: data,
  datatype: "array"
};

let dataAdapter = new $.jqx.dataAdapter(source,
{
  loadComplete: function(data) {},
  loadError: function(xhr, status, error) {}
});

$("#jqxgrid").jqxGrid(
{
  theme: 'energyblue',
  width: 500,
  autoheight: true,
  editable: true,
  source: dataAdapter,
  columns: [{
      text: 'Available',
      datafield: 'available',
      width: 100,
      columntype: 'checkbox'
      
    }, {
      text: 'First Name',
      datafield: 'firstname',
      width: 100
    }, {
      text: 'Last Name',
      datafield: 'lastname',
      width: 100
    }, {
      text: 'Year Eligible',
      datafield: 'yeareligible',
      width: 100
    },
    {
      text: 'Year',
      width: 120,
      datafield: 'yearValue',
      columntype: 'dropdownlist',
      editable: true,
      createeditor: function(row, column, editor) 
      {
        let list = [
          '2010', '2011', '2012', '2013', '2014', '2015', 
          '2016', '2017', '2018', '2019', '2020', '2021'
        ];
        editor.jqxDropDownList({
          autoDropDownHeight: true,
          source: list,
          selectedIndex: 0
        });
      },
      cellsrenderer : (row, columnfield, value, defaulthtml, columnproperties) =>
        $("#jqxgrid").jqxGrid('getrowdata', row).yeareligible === 'N'
          ? '<p>N/A</p>'
          : defaulthtml
    },
    {
      text: 'Product',
      datafield: 'productname',
      width: 180
    }, {
      text: 'Quantity',
      datafield: 'quantity',
      width: 80,
      cellsalign: 'right'
    }, {
      text: 'Unit Price',
      datafield: 'price',
      width: 90,
      cellsalign: 'right',
      cellsformat: 'c2'
    },
    {
      text: 'Total',
      datafield: 'total',
      width: 100,
      cellsalign: 'right',
      cellsformat: 'c2'
    }
  ]
});

// Addendum for OP's purposes
// Set default year to 2016 if available is checked
$("#jqxgrid").on('cellvaluechanged', function (evt)
{
  let args = evt.args;
  if (args.datafield === 'available' && args.newvalue)
  {
    let rowData = $('#jqxgrid').jqxGrid('getrowdata', args.rowindex);
    if (rowData.yeareligible === 'N')
      return;
      
    $('#jqxgrid').jqxGrid('setcellvalue', args.rowindex, 'yearValue', 2016);
  }
});

$('#jqxbutton').click(function() 
{ 
    
  let rows = $('#jqxgrid').jqxGrid('getrows');
  let selectedRows = rows
let count = selectedRows.filter(x => x.available).length;
console.log("Printing selected rows/count length");
  console.log(count);

    rows.filter(x => x.available)
    .map(x => 
      x.yeareligible === 'N'
        ? Object.assign({}, x, {yearValue : '-1'}) 
        : Object.assign({}, {yearValue : '2016'}, x)
    );
  
  console.log(selectedRows);
  
});
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet" />
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet" />
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<div id="jqxgrid"></div>
<input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" />

【问题讨论】:

    标签: javascript jqwidget


    【解决方案1】:
    • 要为年份列显示N/A,您可以为yearValue 列使用自定义cellsrenderer

      cellsrenderer : (row, columnfield, value, defaulthtml, columnproperties) =>
        $("#jqxgrid").jqxGrid('getrowdata', row).yeareligible === 'N'
          ? '<p>N/A</p>'
          : defaulthtml
      

      cellsrenderer 返回您希望在单元格中显示的新原始 html,而不会覆盖基础值。不幸的是,您不能返回元素或 JQuery 对象,但对于简单的 html,它可以正常工作。

    • 要将yearValue : -1 添加到selectedRows,您可以使用map()Object.assign() 返回一个合并的对象。

      let rows = $('#jqxgrid').jqxGrid('getrows');
      let selectedRows = rows
        .filter(x => x.available)
        .map(x => 
          x.yeareligible === 'N'
            ? Object.assign({}, x, {yearValue : '-1'}) 
            : x
        );
      

      API 没有覆盖任何 getter 方法返回的单元格值的函数。有一种方法可以覆盖编辑器值 (geteditorvalue),但这需要通过单元格的编辑器至少设置一次该值,直到第一次编辑单元格时才会创建该值。如果这没有发生,geteditorvalue 将不会被调用,所以你最终还是不得不写一个类似的 map 函数。

      请注意,只要yeareligible'N',这将始终添加yearvalue: '-1',因此您可能需要额外检查yearvalue != null。或者您可能需要考虑是否需要添加该值,因为 yeareligible 已经告诉您所需的信息。


    把它们放在一起:

    let firstNames = [
      "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", 
      "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
    ];
    
    let lastNames = [
      "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", 
      "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", 
      "Vileid", "Saylor", "Bjorn", "Nodier"
    ];
    
    let yearEligible = [
      "Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"
    ];
    
    let productNames = [
      "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", 
      "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", 
      "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
    ];
    
    let priceValues = [
      "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
    ];
    
    let data = [];
    for (let i = 0; i < 10; i++) 
    {
      let productindex = Math.floor(Math.random() * productNames.length);
      let price = parseFloat(priceValues[productindex]);
      let quantity = 1 + Math.round(Math.random() * 10);
      let row = {
        firstname : firstNames[Math.floor(Math.random() * firstNames.length)],
        lastname : lastNames[Math.floor(Math.random() * lastNames.length)],
        yeareligible : yearEligible[Math.floor(Math.random() * lastNames.length)],
        productname : productNames[productindex],
        available : !!(i % 2),
        price : price,
        quantity : quantity,
        total : price * quantity
      };
      data.push(row);
    }
    
    let source = {
      localdata: data,
      datatype: "array"
    };
    
    let dataAdapter = new $.jqx.dataAdapter(source,
    {
      loadComplete: function(data) {},
      loadError: function(xhr, status, error) {}
    });
    
    $("#jqxgrid").jqxGrid(
    {
      theme: 'energyblue',
      width: 500,
      autoheight: true,
      editable: true,
      source: dataAdapter,
      columns: [{
          text: 'Available',
          datafield: 'available',
          width: 100,
          columntype: 'checkbox'
        }, {
          text: 'First Name',
          datafield: 'firstname',
          width: 100
        }, {
          text: 'Last Name',
          datafield: 'lastname',
          width: 100
        }, {
          text: 'Year Eligible',
          datafield: 'yeareligible',
          width: 100
        },
        {
          text: 'Year',
          width: 120,
          datafield: 'yearValue',
          columntype: 'dropdownlist',
          editable: true,
          createeditor: function(row, column, editor) 
          {
            let list = [
              '2010', '2011', '2012', '2013', '2014', '2015', 
              '2016', '2017', '2018', '2019', '2020', '2021'
            ];
            editor.jqxDropDownList({
              autoDropDownHeight: true,
              source: list,
              selectedIndex: 0
            });
          },
          cellsrenderer : (row, columnfield, value, defaulthtml, columnproperties) =>
            $("#jqxgrid").jqxGrid('getrowdata', row).yeareligible === 'N'
              ? '<p>N/A</p>'
              : defaulthtml
        },
        {
          text: 'Product',
          datafield: 'productname',
          width: 180
        }, {
          text: 'Quantity',
          datafield: 'quantity',
          width: 80,
          cellsalign: 'right'
        }, {
          text: 'Unit Price',
          datafield: 'price',
          width: 90,
          cellsalign: 'right',
          cellsformat: 'c2'
        },
        {
          text: 'Total',
          datafield: 'total',
          width: 100,
          cellsalign: 'right',
          cellsformat: 'c2'
        }
      ]
    });
    
    // Addendum for OP's purposes
    // Set default year to 2016 if available is checked
    $("#jqxgrid").on('cellvaluechanged', function (evt)
    {
      let args = evt.args;
      if (args.datafield === 'available' && args.newvalue)
      {
        let rowData = $('#jqxgrid').jqxGrid('getrowdata', args.rowindex);
        if (rowData.yeareligible === 'N')
          return;
          
        $('#jqxgrid').jqxGrid('setcellvalue', args.rowindex, 'yearValue', 2016);
      }
    });
    
    $('#jqxbutton').click(function() 
    {
      let rows = $('#jqxgrid').jqxGrid('getrows');
      let selectedRows = rows
        .filter(x => x.available)
        .map(x => 
          x.yeareligible === 'N'
            ? Object.assign({}, x, {yearValue : '-1'}) 
            : x
        );
    
      console.log(selectedRows);
    });
    <link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet" />
    <link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet" />
    <script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
    <div id="jqxgrid"></div>
    <input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" />

    【讨论】:

    • 感谢您的精彩解释。还有几个问题,1) 是否可以在不让用户单击单元格的情况下显示/显示 jqxdropdown 列表存在,尤其是对于符合条件的年份为 YYear 列?这样,用户就会知道有东西可以点击。 2) 另外,我想知道如果用户没有选择任何内容,我是否可以在 Year 列中显示默认值?例如,默认情况下,屏幕上可能会显示 2016 年,因此如果用户未选择任何内容,则默认值始终与选择一起出现。
    • @Tan 1) 是的。您可以修改cellsrenderer 回调。您可以返回`&lt;p&gt;${value || '[Choose Year]'}&lt;/p&gt;`,而不是返回defaulthtml。 2) 在createeditor 中,为editor 添加一个事件监听器,用于'close' 事件。那么如果editor.val()为空,则选择2016
    • 1) 工作正常。对于#2) - 我不明白这一行In createeditor, add an event listener to editor for the 'close' event. Then if editor.val() is blank, select close 事件在这里有什么意义,因为当用户将Year Eligible 的行标记为Y 时,我想获得2016 的默认值,我应该能够通过以下方式获得2016 的值默认值,如果用户选择其他东西,那么它应该是那个值。再次感谢!
    • @Tan 哦,我误会了。我以为你的意思是如果用户在没有选择的情况下点击菜单。当然,这很容易。使用cellvaluechanged 事件并检查它是否是正确的字段。例如,查看最新编辑。
    • 谢谢。运行您编辑的 sn-p 后,我注意到控制台日志语句中缺少 yearValue。例如,下面的console.log 显示我选择了一条记录,但没有从下拉列表中选择任何内容。但它不包括yearValue: 2016。包括我的console.log 结果作为单独的评论。如果我遗漏了什么,请告诉我。
    猜你喜欢
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多