包含字符串的变量在传递给onclick函数时为空

Variable that contains a string is empty when passed through an onclick function

本文关键字:函数 onclick 字符串 变量 包含      更新时间:2023-09-26

我试图使用onclick事件将字符串传递到函数中。但是,当我单击链接时,函数内的变量什么也不返回。它是空的。当我传递一个数字作为参数时,我没有任何问题,并且在警报中显示没有问题。我不确定我做错了什么。

for (var j=0;j<current_order.length;j++){   
    var note_id = "note" + (j+1);
    text = text + "<button onClick= 'deleteItemfromOrder("+j+")'>Delete</button>";  
    text = text + "<a id = '"+note_id+"' onClick= 'toggleNote("+note_id+")'>Notes</a>";
    alert(text);
}

这是我试图传递note_id到的函数:

function toggleNote(showHideDiv) {
    alert(showHideDiv);
}

我已经尝试了多种方法将字符串作为参数传递给函数EG:

text = text + "<a id = '"+note_id+"' onClick= 'toggleNote('"+note_id+"')'>Notes</a>";

text = text + "<a id = '"+note_id+"' onClick= 'toggleNote(''"+note_id+"';)'>Notes</a>";

但是每次在函数的另一边字符串显示为空时。如果我传递一个数字是没有问题的,例如:

text = text + "<a id = '"+note_id+"' onClick= 'toggleNote("+2+")'>Notes</a>";

你的问题是你缺少引号,数字不需要引号,如

onclick='toggleNote(3)'

但是字符串有

onclick='toggleNote("string")'

同样,使用相同的引号也不起作用

onclick='toggleNote('string')'

意味着你必须做

text = text + "<a id = '"+note_id+"' onClick= 'toggleNote('""+note_id+"'")'>Notes</a>";

但是你真正应该做的是创建元素

for (var j = 0; j < current_order.length; j++) {
    (function(i) {
        var btn = document.createElement('button');
        var anc = document.createElement('a');
        btn.addEventListener('click', function() {
            deleteItemfromOrder(i);
        });
        btn.textContent = 'Delete';
        anc.addEventListener('click', function() {
            toggleNote("note" + (i+1))
        });
        anc.textContent = 'Notes';
    })(j);
}