簡體   English   中英

Javascript中意外的標識符用於循環

[英]Unexpected identifier in Javascript for loop

這似乎可以工作75%的時間,並且使用可用參數執行模態函數,但是表中的每幾個按鈕我都會得到Uncaught SyntaxError:意外標識符。 這與關閉不當有關嗎? 我的Google搜索認為這是一個潛在的問題,但我無法在此處將任何解決方案實施到當前方法中。

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

問題在於, questionTitleanswer1titleanswer2title任何一個answer2title可能在其值中包含單引號,這會破壞您嘗試的字符串連接。 您需要用轉義的單引號替換所有出現的單引號。 所以像這樣:

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 regex。

有更好的方法可以將HTML附加到區域,尤其是在涉及表格時。 我建議使用jQuery而不是內聯綁定事件。 這是一個不同的主題,並且與您的問題無關,盡管它可以從一開始就避免它。

可能是您應該在添加到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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM