2

这似乎在 75% 的时间内有效,并且模态函数使用可用的参数执行,但表中每隔几个按钮我就会得到一个 Uncaught SyntaxError: Unexpected identifier。这与关闭不当有关吗?我的谷歌搜索发现这是一个潜在问题,但我无法在我当前的方法中实施任何解决方案。

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); 
4

2 回答 2

1

问题是任何questionTitle, answer1title, oranswer2title的值中可能有一个单引号,这会破坏您尝试的字符串连接。您需要用转义的单引号替换所有出现的单引号。所以是这样的:

http://jsfiddle.net/ZYnfc/2/

$(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);
}

您必须以我的示例并将其应用到您的实际代码中,但重点是在函数调用中连接的每个变量的replace方法和正则表达式的使用。replacer

有更好的方法将 HTML 附加到区域,尤其是在涉及到表格时。我建议使用 jQuery 绑定事件,而不是内联。这是一个不同的主题,与您的问题无关,尽管它本来可以帮助避免它。

于 2012-12-17T08:24:24.687 回答
0

可能是您应该在添加到 onclick 属性之前转义字符串:

+ '<button onclick="openQuestionModal(\''+ escape(questionTitle)+'\', \''+ escape(answer1title)+'\', \''+escape(answer2title)+'\')" class="btn btn-small btn-primary" id="questionEdit" type="button">Edit</button>'

并使用:

unescape('str_to_revert')// to get the data back inside your function.
于 2012-12-17T08:01:59.443 回答