我正在尝试使用 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);
}
关于javascript - 通过 onclick 函数传递时,包含字符串的变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621569/