簡體   English   中英

javascript循環:變量等於最后一次迭代

[英]javascript loop: variable equals the last iteration

用戶單擊添加更多鏈接后,下面的代碼將添加元素。

當用戶單擊刪除鏈接時,問題就來了。

我的代碼中有類似的內容

<script language="JavaScript">
var count=1;
function addmore() {
    alert(count);
    var printme = "<table id='table"+count+"'><tr><td><a href='#' onclick='remove(count)'>remove</a></td></tr></table";
    //(other code here)...
    count++;
}

function remove(y) {
    alert(y)
    var tab = 'table'+y;    
    document.getElementById(tab).style.display =  "none";
}
</script>

我在這里使用了警報,因此我可以輕松地監視它給出的計數值。

此處發生的是'y'的值(在刪除功能上)始終相同,這是循環中count的最后一個值。

例如,我單擊鏈接addmore 3次,因此我的“ count = 4”的最后一個值。 假設我要刪除第三個元素,這時我單擊刪除鏈接時,它必須具有pass參數,例如remove(3)。 但是這里發生的是我單擊的任何元素,好像它總是以這種方式傳遞參數remove(4)

那是因為您已經count一個全局變量。

嘗試.....onclick='remove("+count+")'....對值進行“鎖定”。

請嘗試以下方法:

var printme = "<table id='table"+count+"'><tr><td><a href='#' onclick='remove("+count+")'>remove</a></td></tr></table";

還可以嘗試以下行刪除功能:

document.getElementById(""+tab+"").style.display =  "none";

也許只是onclick ='remove('+ count +')'

你可以做類似的事情

<html>
<head>
<script type="text/javascript">
var count=1;
function addmore() {
    var id = 'table' + count;
    var table = document.createElement('table');
    table.setAttribute('id', id);
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var a = document.createElement('a');
    a.setAttribute('href', '#');
    a.appendChild(document.createTextNode('remove ' + id));
    a.onclick = function() {
        table.style.display = 'none';
        document.body.removeChild(table);
    };
    td.appendChild(a);
    tr.appendChild(td);
    table.appendChild(tr);
    document.body.appendChild(table);
    count++;
}
</script>
</head>
<body>
<a href="#" onclick="addmore()">Add Table</a>
</body>
</html>

使用表引用和onclick這樣定義,您不需要ID

先前的所有答案都是正確的,在調用remove時,onclick表示當前變量計數。

當您為表格生成文本時,請按原樣使用count的值:

onclick='remove('+count+')...

您可以使用以下方法省略ID並進行總數計算:

onclick='remove(this.parentElement.parentElement.parentElement);'...

function remove(elementToRemove){
    elementToRemove.parentElement.removeChild(elementToRemove);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM