Javascript for循环中的意外标识符
这似乎在75%的时间内都能正常工作,模态函数使用可用的参数执行,但表中的每几个按钮我都会得到一个未捕获的SyntaxError:意外标识符。这与inproper闭包有关吗?我在谷歌上的搜索发现这是一个潜在的问题,但我无法在我目前的方法中实现任何解决方案Javascript for循环中的意外标识符,javascript,loops,buttonclick,Javascript,Loops,Buttonclick,这似乎在75%的时间内都能正常工作,模态函数使用可用的参数执行,但表中的每几个按钮我都会得到一个未捕获的SyntaxError:意外标识符。这与inproper闭包有关吗?我在谷歌上的搜索发现这是一个潜在的问题,但我无法在我目前的方法中实现任何解决方案 html += '<thead><th>Question</th><th>Answer 1</th><th>Answer 2</th><th>Answ
html += '<thead><th>Question</th><th>Answer 1</th><th>Answer 2</th><th>Answer 3</th><th>Answer 4</th></thead>';
for (var i = 0; i < questions.length; i++) {
question = questions[i].question;
questionTitle = question.q;
answer1title = question.a1;
answer2title = question.a2;
html += '<tr><td class="question"><b>'
+ question.q
+ '</b></td><td class="answer1">'
+ question.a1
+ '</td><td class="answer2">'
+ question.a2
+ '</td><td class="answer3">'
+ question.a3
+ '</td><td class="answer4">'
+ question.a4
+ '</td><td class="edit">'
+ '<button onclick="openQuestionModal(\''+questionTitle+'\', \''+answer1title+'\', \''+answer2title+'\')" class="btn btn-small btn-primary" id="questionEdit" type="button">Edit</button>'
+ '</td></tr>';
}
$('#questionsTable').append(html);
html+=“问题答案1回答2回答3回答4”;
对于(var i=0;i
可能是,在添加到onclick属性之前,您应该转义字符串:
+ '<button onclick="openQuestionModal(\''+ escape(questionTitle)+'\', \''+ escape(answer1title)+'\', \''+escape(answer2title)+'\')" class="btn btn-small btn-primary" id="questionEdit" type="button">Edit</button>'
问题是,
questionTitle
、answer1title
或answer2title
中的任何一个值都可能有一个引号,这会中断您尝试的字符串连接。您需要用转义的单引号替换单引号的所有引用。比如说:
$(文档).ready(函数(){
Var PA= =“我是问题”;
var replacer=new RegExp(“'”,“g”);
var new_btn=$(“你从哪里得到你的问题
以及它看起来怎么样?问题标题
,回答标题
,或回答标题
中是否有单引号/双引号?我想部分或多个标记没有关闭,因此出现语法错误。未捕获语法错误:意外标识符-bec因为,问题的内容可能包含导致此问题的文字。questionTitle
或answer1title
或answer2title
包含一个引号”
。我没有否决,但我尝试过。它修复了错误,但现在我传递的所有数据都加载了特殊字符(%20等)这不是你想象中的转义。这个escape
函数用于转义URL,对于转义单个引号来说确实是不必要的,这是主要的问题。我可以在整个数组上运行这个函数来消除问题,甚至在我开始循环之前吗?我还想看看关于如何附加HTML的更好的示例。我当然可以n学习更好的实践。
unescape('str_to_revert')// to get the data back inside your function.
$(document).ready(function () {
var par = "I'm the problem";
var replacer = new RegExp("'", "g");
var new_btn = $('<button onclick="clicker(\'' + par.replace(replacer, "\\'") + '\');">ASDF</button>');
$("#main").append(new_btn);
});
function clicker(param) {
alert(param);
}