【问题标题】:My aim is to get a button,when clicked the button the table to should be displayed,but the data is displayed beforehand and the button does nothing我的目标是获得一个按钮,当单击该按钮时应该显示表格,但数据是预先显示的,按钮什么也不做
【发布时间】:2021-09-29 01:36:31
【问题描述】:

获取 JSON 数据并将其显示在表格中。下面的代码只是一个骨架结构,但是我正在创建的按钮什么也不做,尽管我正在尝试向按钮(单击)添加一个事件,该事件将根据函数 tablechange() 显示表格。表格已经在我单击按钮之前显示。请帮忙。

var  request= new XMLHttpRequest();
request.open('GET','https://raw.githubusercontent.com/Rajavasanthan/jsondata/master/pagenation.json',true);

request.send();

request.onload=function(){
var data=JSON.parse(request.response);
console.log(data);

var table=document.createElement('table');
table.setAttribute('class','table');
var thead=document.createElement('thead');
thead.setAttribute('class','thead-dark')
var tr=document.createElement('tr');
var tbody=document.createElement('tbody');


var th1=document.createElement('th')
th1.innerHTML='id'
var th2=document.createElement('th');
th2.innerHTML='Name'
var th3=document.createElement('th');
th3.innerHTML='Email';

tr.append(th1,th2,th3);
thead.append(tr);
table.append(thead);


var divis=document.createElement('div');
divis.setAttribute('style','padding:20px');
var button=document.createElement('button');
button.innerHTML="click me";
button.addEventListener('click',tablechange(3));
divis.append(button);
document.body.append(divis);

function tablechange(i=1){
    for(let x=i*5;x<((i+1)*5);x++){
        let k=data[x];
       
    var td1=document.createElement('td');
    var td2=document.createElement('td');
    var td3=document.createElement('td');
    td1.innerHTML=k.id
    td2.innerHTML=k.name;
    td3.innerHTML=k.email;
    var tr=document.createElement('tr');
    if(x%2===0) tr.setAttribute('style','background-color:#d3d3d3');
    tr.append(td1,td2,td3);
    tbody.append(tr);
    table.append(tbody);

document.body.append(table);
}
}
}
 

【问题讨论】:

  • addEventListener代码更改为button.addEventListener("click", tablechange.bind(null,3), false);

标签: javascript html xmlhttprequest


【解决方案1】:

button.addEventListener('click',tablechange(3)); 你正在调用函数tablechange(3) 马上

addEventListener 应该是

button.addEventListener("click", tablechange.bind(null,3), false);

【讨论】:

【解决方案2】:

你在初始化时调用你的函数 tablchange(3) 因为你有 () 调用括号。为了让它只在点击时调用,它应该是

button.addEventListener('click',tablechange)

当然你不能像这样传递参数,所以你需要将参数设置为你的函数可以访问的变量。

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多