HY,
基本上,我有一些动态生成的列表项,其中包含一个按钮。当我将列表项添加到ul列表之前,当我单击列表项中的按钮时,我可以访问我想要传递的变量。但是当我在下面显示的代码行中添加变量时,它会给我一个Uncaught ReferenceError: challenger is not defined
错误。我怎样才能传递这些变量?
JAVASCRIPT:
window.GLOBAL_socket.on('challenged', function(data) {
console.log("You have been challenged by the player " + data.challenger);
var challenged = getUrlVars()['user'];
var challenger = data.challenger;
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>" + data.challenger +
"</p><input type='button' value='ACCEPT' id='challenge_accept' onclick='acceptChallenge(challenger)'></input><input type='button' value='DECLINE' " +
"id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
});
onclick方法可在第6行找到。
感谢您的回复,
芝诺
答案 0 :(得分:3)
未定义挑战者的原因是因为它是一个局部变量,并且当您通过点击实际触发该功能时无法全局访问。
因此,不要使用变量,只需在onclick中放置它的实际值。
将您的代码更改为:
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>" + data.challenger +
"</p><input type='button' value='ACCEPT' id='challenge_accept' onclick='acceptChallenge(\""+challenger+"\")'></input><input type='button' value='DECLINE' " +
"id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
答案 1 :(得分:0)
按照我在评论中提到的更改您的代码。
var challenged = [];
var challenger = [];
var counter = 0;
window.GLOBAL_socket.on('challenged', function(data) {
console.log("You have been challenged by the player " + data.challenger);
counter++;
challenged[counter] = getUrlVars()['user'];
challenger[counter] = data.challenger;
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>"
+ data.challenger
+ "</p><input type='button' value='ACCEPT' id='challenge_accept'"
// change of code --> passing value directly into the function
+ " onclick='acceptChallenge(challenger["+counter+"]
+")'></input><input type='button' value='DECLINE' "
+ "id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
});
我刚刚修改了代码,希望它适合你。让我知道