【问题标题】:Add/Remove Table Columns in JavaScript Based On Checkbox Status基于复选框状态在 JavaScript 中添加/删除表列
【发布时间】:2019-01-02 22:40:40
【问题描述】:

如果您将列表粘贴到搜索框中,则在以下 DEMO 中:

00001, 00002, 00003, 00004, 00005, 00006, 00007, 00008, 00009, 00010, 00011, 00012, 00013

它将从位于此处的 JSON 文件中提取相应的属性特征: https://api.myjson.com/bins/f2nos

var data = {};

$(document).ready(function () {
    $("#Search").click(function (any) {
		$("tbody").empty();
        var searchIds = new Set($('#searchBox').val().split(/[ ,\r\n]+/).map(s => s.trim()));
        searchIds.forEach(CODE =>
			
            $("tbody").append('<tr>' + `<td class="theader1" id="theader1">${CODE}</td>` + `<td class="theader2" id="theader2">${datab[CODE]}</td>` + `<td class="theader3" id="theader3">${datac[CODE]}</td>` + `<td class="theader4" id="theader4">${datad[CODE]}</td>` + '</tr>'));
    });
});

function getdata() {
    fetch("https://api.myjson.com/bins/f2nos").then(resp => resp.json()).then(resp => {
        datab = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, DIVISION}}) => ({ [CODE]: DIVISION}))
        );
        datac = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, PROVINCE}}) => ({ [CODE]: PROVINCE}))
        );
        datad = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, NAME}}) => ({ [CODE]: NAME}))
        );		
    });
}

getdata();						
	
/*Checkbox To Table Head*/
$("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).hide();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});
  <head>
   <title>Code Table</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>
  <body>
	<span class="clearable">
		<input id="searchBox" type="text" rows="25" cols="15" WRAP="HARD" placeholder="Paste the list HERE" type="search">
	</span>
	<button class="button button1" id="Search">Search</button>	
	</br>
	<p><input type="checkbox" class="theader1" name="theader1" checked="checked"> CODE
  <input type="checkbox" class="theader2" name="theader2" checked="checked"> DIVISION
  <input type="checkbox" class="theader3" name="theader3" checked="checked"> PROVINCE
  <input type="checkbox" class="theader4" name="theader4" checked="checked"> NAME</p>
	</br>
		<table border="1px" id="data">
			<thead>
			<tr>
			<th class="theader1" id="theader1">CODE</th>
			<th class="theader2" id="theader2">DIVISION</th>
			<th class="theader3" id="theader3">PROVINCE</th>	
			<th class="theader4" id="theader4">NAME</th>
			</tr>
			</thead>
			<tbody></tbody>
		</table>

复选框控制表格列是否可见。

因此,如果您取消选中复选框 CODE,CODE 列将消失

一个小问题。

当我在搜索之前取消选中任何复选框时,例如 CODE,然后搜索我得到这个奇怪的表:

发生这种情况的原因是即使未选中该复选框,APPEND() 语句仍会附加 CODE 列。

那么如何将复选框状态连接到附加语句,以便即使在搜索之后也不会显示列?

我假设解决方案是将每个 Table TD 变成一个变量,并以某种方式将其连接到复选框的状态?

如何做到这一点?还是更好的解决方案?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    “那么如何将复选框状态连接到附加语句,以便即使在搜索之后也不会显示列?”

    “我假设解决方案是将每个 Table TD 变成一个变量,并以某种方式将其连接到复选框的状态?”

    “如何做到这一点?或者更好的解决方案?”

    您是对的,这是将行附加到表中的方式,而不检查是否未选中任何复选框。以下是所做的更改:

    • 所有复选框只有一个类:.theader

    • 所有&lt;td&gt; 都删除了#ids,重复#ids 是无效的HTML,而且无论如何它都没有任何用处。

    • 下面是关于列生成问题的解决方法:

       searchIds.forEach(CODE => {
         // Row template stored as an array of strings 
         var theader = [
           `<td class="theader1">${CODE}</td>`, 
           `<td class="theader2">${datab[CODE]}</td>`,
           `<td class="theader3">${datac[CODE]}</td>`, 
           `<td class="theader4">${datad[CODE]}</td>`
         ];
         // <tr> is appended before <td> is generated 
         $("tbody").append('<tr></tr>');
         // Each checkbox...
         $('.theader').each(function(idx) {
            // ...that is checked... 
            if ($(this).is(':checked')) {
              // ...will append the string from the array according to current index
              $("tbody tr:last").append(`${theader[idx]}`);
            }
         });
      });
    

    var datab, datac, datad;
    $("#Search").click(function() {
      $("tbody").empty();
    
      var searchIds = new Set($('#searchBox').val().split(/[ ,\r\n]+/).map(s => s.trim()));
    
      searchIds.forEach(CODE => {
    
        var theader = [`<td class="theader1">${CODE}</td>`, `<td class="theader2">${datab[CODE]}</td>`, `<td class="theader3" >${datac[CODE]}</td>`, `<td class="theader4">${datad[CODE]}</td>`];
        $("tbody").append('<tr></tr>');
        $('.theader').each(function(idx) {
    
          if ($(this).is(':checked')) {
            $("tbody tr:last").append(`${theader[idx]}`);
          }
        });
      });
    });
    
    
    function getdata() {
      fetch("https://api.myjson.com/bins/f2nos").then(resp => resp.json()).then(resp => {
        datab = Object.assign({}, ...resp.features.map(
          ({
            properties: {
              CODE,
              DIVISION
            }
          }) => ({
            [CODE]: DIVISION
          })));
        datac = Object.assign({}, ...resp.features.map(
          ({
            properties: {
              CODE,
              PROVINCE
            }
          }) => ({
            [CODE]: PROVINCE
          })));
        datad = Object.assign({}, ...resp.features.map(
          ({
            properties: {
              CODE,
              NAME
            }
          }) => ({
            [CODE]: NAME
          })));
      });
    }
    
    getdata();
    
    /*Checkbox To Table Head*/
    $(".theader:not(:checked)").each(function() {
      var column = "table ." + $(this).attr("name");
      $(column).hide();
    });
    
    $(".theader").click(function() {
      var column = "table ." + $(this).attr("name");
      $(column).toggle();
    });
    <head>
      <title>Code Table</title>
    
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>
    
    <body>
      <fieldset>
        <input id="searchBox" placeholder="Paste the list HERE" type="search">
    
        <button type="button" id="Search">Search</button>
        <br><br>
        <input type="checkbox" class="theader" name="theader1" checked="checked"> CODE
        <input type="checkbox" class="theader" name="theader2" checked="checked"> DIVISION
        <input type="checkbox" class="theader" name="theader3" checked="checked"> PROVINCE
        <input type="checkbox" class="theader" name="theader4" checked="checked"> NAME
    
      </fieldset>
      <br>
      <table border="1px" id="data">
        <thead>
          <tr>
            <th id="theader1" class="theader1">CODE</th>
            <th id="theader2" class="theader2">DIVISION</th>
            <th id="theader3" class="theader3">PROVINCE</th>
            <th id="theader4" class="theader4">NAME</th>
          </tr>
        </thead>
        <tbody>
    
        </tbody>
      </table>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    【讨论】:

    • 确实,编码愉快。
    【解决方案2】:

    var data = {};
    
    $(document).ready(function () {
        $("#Search").click(function (any) {
    		$("tbody").empty();
            var searchIds = new Set($('#searchBox').val().split(/[ ,\r\n]+/).map(s => s.trim()));
            searchIds.forEach(CODE =>
    			
                $("tbody").append('<tr>' + `<td class="theader1" id="theader1">${CODE}</td>` + `<td class="theader2" id="theader2">${datab[CODE]}</td>` + `<td class="theader3" id="theader3">${datac[CODE]}</td>` + `<td class="theader4" id="theader4">${datad[CODE]}</td>` + '</tr>'));
        });
    });
    
    function getdata() {
        fetch("https://api.myjson.com/bins/f2nos").then(resp => resp.json()).then(resp => {
            datab = Object.assign({}, ...resp.features.map(
                ({ properties: { CODE, DIVISION}}) => ({ [CODE]: DIVISION}))
            );
            datac = Object.assign({}, ...resp.features.map(
                ({ properties: { CODE, PROVINCE}}) => ({ [CODE]: PROVINCE}))
            );
            datad = Object.assign({}, ...resp.features.map(
                ({ properties: { CODE, NAME}}) => ({ [CODE]: NAME}))
            );		
        });
    }
    
    getdata();						
    	
    /*Checkbox To Table Head*/
    $(document).ready(function(e) {
        
    
    $("input:checkbox:not(:checked)").each(function() {
    	var apndcss='';
        var column = "table ." + $(this).attr("name");
    	apndcss+=column+"{display:none;}";
    	$('#appnedcss').html(apndcss)
        console.log(apndcss);
    });
    
    $("#chkbtn").on('change','input',function(){
    var apndcss='';
    $("#chkbtn input:checkbox").each(function() {
    if($(this).is(":not(:checked)")){
    var column = "table ." + $(this).attr("name");	
    apndcss+=column+"{display:none;}";
    }
    })
    $('#appnedcss').html(apndcss)
    })
    });
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
     <style id="appnedcss"></style> 
    </head>
    <body>
    
      <body>
    	<span class="clearable">
    		<input id="searchBox" type="text" rows="25" cols="15" WRAP="HARD" placeholder="Paste the list HERE" type="search">
    	</span>
    	<button class="button button1" id="Search">Search</button>	
    	</br>
    	<p id="chkbtn"><input type="checkbox" class="theader1" name="theader1" checked="checked"> CODE
      <input type="checkbox" class="theader2" name="theader2"  checked="checked"> DIVISION
      <input type="checkbox" class="theader3" name="theader3" checked="checked"> PROVINCE
      <input type="checkbox" class="theader4" name="theader4" checked="checked"> NAME</p>
    	</br>
    		<table border="1px" id="data">
    			<thead>
    			<tr>
    			<th class="theader1" id="theader1">CODE</th>
    			<th class="theader2" id="theader2">DIVISION</th>
    			<th class="theader3" id="theader3">PROVINCE</th>	
    			<th class="theader4" id="theader4">NAME</th>
    			</tr>
    			</thead>
    			<tbody></tbody>
    		</table>
    
    
    
    </body>
    </html>

    【讨论】:

    • 正是我所要求的!非常感谢!
    • @Discover 是否对您有帮助 正确检查此答案
    • 我每个问题只能做一个检查,另一个答案更快
    猜你喜欢
    • 2011-06-27
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多