【发布时间】:2015-01-22 22:46:22
【问题描述】:
这是指我之前的问题。
how to filter records based on key click?
但现在我正在尝试在 div 元素数组和表之间进行通信,那么我如何根据 div 数组过滤记录。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() { // on page load
$('#myElId').data('nameYourData', ["22","23","24"]);
var myData = $('#myElId').data('nameYourData');
$("#showMyData").text(myData);
});
</script>
</head>
<body>
<div id="myElId">Some element</div><br/>
MyData:<div id="showMyData"></div>
<a href="filter_records()">MyData:<div id="showMyData"></div></a>
<script>
$(function() {
$('input[type="checkbox"]').change(function() {
// We check if one or more checkboxes are selected
// If one or more is selected, we perform filtering
if($('input[type="checkbox"]:checked').length > 0) {
// Get values all checked boxes
var vals = $('input[type="checkbox"]:checked').map(function() {
return this.value;
}).get();
// Here we do two things to table rows
// 1. We hide all
// 2. Then we filter, show those whose value in first <td> matches checkbox value
$('table tr')
.hide() // 1
.filter(function() { // 2
return vals.indexOf($(this).find('td:first').text()) > -1;
}).show();
} else {
// Show all
$('table tr').show();
}
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border =1 cellspacing="1" cellpadding="1" style="width:100%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Marks</th>
</tr>
<tr>
<td>22</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>23</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>45</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>24</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>25</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>29</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<input type="checkbox" name="vehicle" value="22"> 22<br>
<input type="checkbox" name="vehicle" value="23"> 23 <br>
<input type="checkbox" name="vehicle" value="24"> 24<br>
<input type="checkbox" name="vehicle" value="25"> 25 <br>
<input type="checkbox" name="vehicle" value="29"> 29<br>
<input type="checkbox" name="vehicle" value="45"> 45 <br>
</body>
</html>
但是我如何通过单击文本(如 href)来实现它,并且应该在函数中传递 showdata 变量并且应该过滤行。
【问题讨论】:
-
您是说您有几个 div 对应于表中数据的不同部分?通过点击相应的div,隐藏表中与该div无关的其他数据?
-
是的,我有很多 div
-
只是一个注释,你不需要加载jQuery两次。一次就够了。
-
你可以发布示例,因为我不擅长 JS/JQuery,但我是 C 程序员。
-
@DavidBarker 一次就够了吗?所以他根本不需要加载jQuery?
标签: javascript jquery arrays