简体   繁体   English

使用 onclick 内部字符串 for loop 调用 function

[英]call function using onclick inside string for loop

I am creating a table depending on the result of a function for then append in a div like this:我正在根据 function 的结果为 append 创建一个表,如下所示:

    let result = document.getElementById("result");
    consultCities();
    
    function consultCities (){
        consultarAPI(username, password, "cities")
        .then((response) => {
            if(response.login !== "Fail"){
                let table = "";
                let thead = "";
                let tbody = "";
    
                thead += `<tr>
                            <th>Citie</th>
                            <th>Dane</th>
                            <th>Look Institution</th>
                          </tr>`
                for(let i = 0; i < response.data.length;  i += 1 ){
    
                    tbody += `<tr>
                                    <td>${response.data[i].name}</td>
                                    <td>${response.data[i].dane}</td>
                                    <td><button type="button" id="ver" onclick="${consultInstitutions(response.data[i].dane)}">Ver</button></td>
                               </tr>`
                }
    
                table += `<table class="table table-bordered">
                            <thead>
                                ${thead}
                            </thead>
                            <tbody>
                                ${tbody}
                            </tbody>
                          </table>`
    
                result.innerHTML = table;
            }else{
                alert("El Usuario no existe o la opción no existe");
            }
        });
    }

function consultInstitutions(codCity){
    console.log(codCity);
}

The problem is the onclick trigger runs automatically although I don't click in any button, my question is there a best way that I can set onclick a button for a string?问题是 onclick 触发器会自动运行,尽管我没有单击任何按钮,我的问题是我可以将 onclick 设置为字符串按钮的最佳方法吗?

I think the issue here is that you are running the function immediately by placing it within ${} .我认为这里的问题是您通过将 function 放在${}中立即运行它。 Instead you just want to place the variable within the ${} .相反,您只想将变量放在${}中。

onclick="consultInstitutions(${response.data[i].dane})"

Here is an alternative version of your script.这是您的脚本的替代版本。 I took the liberty of inventing some test data in order to make it an MCVE.我冒昧地发明了一些测试数据,以使其成为 MCVE。

 const D={login:"OK",data:[ {name:"Rome",dane:"Gio"}, {name:"Kiev",dane:"Ivan"}, {name:"Paris",dane:"Lorraine"}, {name:"Ohio",dane:"Matt"}, {name:"Minsk",dane:"Sergey"}]}, tbl = document.getElementById("result"); tbl.innerHTML=makeTable(D); tbl.onclick=ev=>{ if(ev.target.tagName==="BUTTON") console.log(ev.target.closest("td").previousElementSibling.textContent) } function makeTable(resp){ if(resp.login.== "Fail") return `<table class="table table-bordered"><thead><tr><th>Citie</th><th>Dane</th><th>Look Institution</th></tr></thead><tbody>` + resp.data.map(r=> `<tr><td>${r.name}</td><td>${r.dane}</td><td><button type="button">Ver</button></td></tr>`);join("\n") + "</tbody></table>"; else alert("El Usuario no existe o la opción no existe"); }
 <div id="result"></div>

I used a delegated attachment handling: The click event is listened to by the <table> element but the action only happens if the clicked element ( ev.target ) happens to be a "BUTTON".我使用了委托附件处理: <table>元素侦听单击事件,但仅当单击的元素( ev.target )恰好是“按钮”时才会发生该操作。 In that case the function looks for the text content of the previous <TD> element and cinsole.log() s it.在这种情况下,function 会查找前一个<TD>元素的文本内容,然后cinsole.log()它。 Doing it this way I can keep the HTML-template strings in my markup generator function makeTable() very simple.这样做我可以在我的标记生成器 function makeTable()中保持 HTML 模板字符串非常简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM