简短描述:
01) 我将数据从 JSON url 动态加载到 HTML 表中。该脚本位于外部 .js
HTML
的 header 中调用的文件文件。
02) 我使用页面顶部第一列 (NAME) 的过滤器来过滤结果。如果我将脚本包含在 <script>
下的 HTML 文件中,该脚本就会起作用。标签,但当我将所有函数放在外部 .js
中时它不起作用文件。
链接如下所示:LINK
JS 脚本在这里:
//It loads the data from the JSON file
$.getJSON(
'http://apolosiskos.co.uk/TEB/MOCK_DATA.json',
function(data){
var tr;
//It loads data from the JSON file to the table
$.each (data, function (key, val) {
tr = $('<tr/>');
tr.append('<td class="name" rel="' + val.first_name + '">' + val.first_name + '</td>');
tr.append('<td >' + 'TEST' + '</td>');
tr.append('<td class="metric2" >' + val.id + '</td>');
tr.append('<td class="metric3"><span class="multTotal">' +'0.00'+ '</span></td>');
tr.append('<td class="metric3-100"><span class="metric3-100">' +'0.00'+ '</span></td>');
tr.append('<td class="metric1-100"><span class="metric1-100">' +'0.00'+ '</span></td>');
$('table').append(tr);
});
});
//The filter function for the first column (NAME)
$("input:checkbox").click(function filters() {
var showAll = true;
$('tr').not('.first').hide();
$('input[type=checkbox]').each(function () {
if ($(this)[0].checked) {
showAll = false;
var dimension1= $(this).attr('rel');
var value = $(this).val();
$('td.' + dimension1+ '[rel="' + value + '"]').parent('tr').show();
}
});
if(showAll){
$('tr').show();
}
});
$('body').on('input', 'input:checkbox', filters);
最佳答案
关于过滤器函数,您在 .click(function filter() { ... });
内命名了该函数,并且在您尝试在“.click”之外使用之后$('body').on('input', 'input:checkbox', 过滤器);
我认为你必须做类似的事情
function filters(){ ... };
$("input:checkbox").click( filters );
$('body').on('input', 'input:checkbox', filters);
或者更好的是,您不需要使用.click
,只需尝试这样使用:
$('body').on('click', 'input:checkbox', function(){
var showAll = true;
$('tr').not('.first').hide();
$('input[type=checkbox]').each(function () {
if ($(this)[0].checked) {
showAll = false;
var dimension1= $(this).attr('rel');
var value = $(this).val();
$('td.' + dimension1+ '[rel="' + value + '"]').parent('tr').show();
}
});
if(showAll){
$('tr').show();
}
});
这样,您就可以将点击事件附加到 body
上存在的每个 input:checkbox
上,并且也将附加到新的输入
关于javascript - 使用困惑的查询(HTML 表)从 JSON url 添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509653/