我有以下html:
div id="parentanswer">
<div id="parent0" class="control-group" style="margin: 0;">
<label class="control-label">Answer</label>
<div id="answer0" class="controls">
<input type="text" class="span6 m-wrap" />
<select name="answerCountry" id="answercountry0" class="select2"><option value="DA">Danmark</option><option value="EN">Engelsk</option><option value="GE">Tysk</option><option value="SE">Svensk</option></select>
Right answer<input type="checkbox" value="" />
</div>
<p style="padding: 0; margin: 0; padding-left: 180px;"><a href id="translateanswer0" answertranslateid="0">Translate answer</a></p>
</div>
</div>
<p style="padding: 0; margin: 0; padding-left: 180px;"><a href id="addanswer">Add new answer</a></p>
和下面的jQuery:
$("[id^=translateanswer]").on("click", function () {
alert($(this).attr('answertranslateid'));
answerid = $(this).attr('answertranslateid');
newtranslateid = '#answer' + answerid;
answerselectid = 'answerCountry' + answerid;
alert(newtranslateid);
$("<div style=\"padding: 0; margin: 0;\" class=\"controls\"><input type=\"text\" class=\"span6 m-wrap\" /> <select name=\"answerCountry\" id=\"" + answerselectid + "\" class=\"select2\"><option value=\"DA\">Danmark</option><option value=\"EN\">Engelsk</option> <option value=\"GE\">Tysk</option><option value=\"SE\">Svensk</option></select> </div>").appendTo(newtranslateid);
return false;
});
$('#addanswer').on("click", function () {
counter++;
newtranslateid = counter;
alert(newtranslateid);
newquestionid = 'answer' + counter;
newtranslateanswerid = 'translateanswer' + counter;
answerselectid = 'answercountry' + counter;
newparentid = 'parent' + counter;
$("<div id=\"" + newparentid + "\" class=\"control-group\" style=\"margin: 0;\"><label class=\"control-label\">Answer</label><div id=\"" + newquestionid + "\" class=\"controls\"><input type=\"text\" class=\"span6 m-wrap\" /><select name=\"answerCountry\" id=\"" + answerselectid + "\" class=\"select2\"><option value=\"DA\">Danmark</option><option value=\"EN\">Engelsk</option><option value=\"GE\">Tysk</option><option value=\"SE\">Svensk</option></select> Right answer<input type=\"checkbox\" value=\"1\" /></div><p style=\"padding: 0; margin: 0; padding-left: 180px;\"><a href id=\"" + newtranslateanswerid + "\" answertranslateid=\"" + newtranslateid + "\">Translate answer</a></p> </div>").appendTo('#parentanswer');
return false;
});
当我在 html 代码中单击“翻译答案”时,效果很好,并将正确的 html 附加到我的网站,“添加新答案”也是如此。
当我添加了一个新问题并想翻译它并单击“翻译答案”时,就会出现问题。然后我的网站只是重新加载,而不调用 $("[id^=translateanswer]").on("click", function(){
我试过“硬编码”一个答案1,然后调用“翻译答案”,效果很好,我还尝试清空翻译答案功能,只是发出警报,但它没有提醒消息。我怀疑故障出在 addanswer 函数中,但我找不到。
我创建了一个jsfiddle,但它说了一些关于使用 post 的内容?
更新了 jsfiddle:http: //jsfiddle.net/4cTBP/