【问题标题】:Onclick global function with local parameter带有本地参数的 Onclick 全局函数
【发布时间】:2019-10-15 23:49:50
【问题描述】:

a question about ordering XHR functions之后的跟进 这是一种递归情况,其中 sendRequest() 正在创建一个带有指向自身的 onclick 链接的字段。此 onclick 链接存储变量 word,应在调用时提供给 sendRequest。

<script type="text/javascript">
function inputReq(){
    sendRequest(wordform.word.value)
}
function sendRequest(str){
    //we start by removing the now superfluous rows
    table=document.getElementById('table')
    while(table.rows.length>2){
        table.deleteRow(2);
    }
    var request = new XMLHttpRequest();
    console.log('sending request');
    request.open('GET', 'http://127.0.0.1:5000/api.html?query='+str, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            json=request.responseText;
            console.log(json);
            //json.forEach(function(obj) { 
            //});
            for (word in json){
                var row=table.insertRow();
                var scoreC=row.insertCell();
                var wordC=row.insertCell();
                scoreC.innerHTML=json[word];
                wordC.innerHTML=word;
                wordC.onclick=(function(i)  {sendRequest(i);})(word);
            }
        } else {
            console.log("Silence on the line");
        }
    }
    request.send();
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Query Page</title>
</head>
<body>
<h1>Query Page</h1>

<table id='table' style="width:100%">
<tr><form name='wordform'>
    <th>Concept: <input type="text" name="word"></th>
    <th><input type="button" onclick="inputReq()" value='Find Associations'></th>
</form></tr>
</body>
</html>

XHR 响应如下所示:

{"milk": 1, "cheese": 3, "bread": 2}

我一直在关注this schema,但这一行是调用函数而不是添加 onclick 链接:

wordC.onclick=(function(i)  {sendRequest(i);})(word);

【问题讨论】:

    标签: javascript html arrays function object


    【解决方案1】:

    因为它是一个 IIFE(立即调用函数表达式),所以它会被立即调用。在它周围放置另一个函数。

    wordC.onclick = () => (function(i) { sendRequest(i); })(word);
    

    (上面看起来不像有环绕函数,但确实有——它是一个 ES6 箭头函数)。

    【讨论】:

    • 对剩余代码进行一些修正后,生成了onclick函数
    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多