问题描述
|
这似乎很奇怪,但是使用jQuery
replace()
似乎仅在alert()
或console.log
中运行时才有效。
这是我要运行的代码:
$(\'.settings_item[data-slide-id=1324] .answers_fields_template li\').each(function(index) {
var regexp = new RegExp(\'new_answers\',\'g\');
var new_id = new Date().getTime();
$(this).html().replace(regexp,new_id);
});
这是HTML代码:
<li data-weight=\"1\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_skeleton\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][skeleton]\" type=\"hidden\" value=\"true\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_text\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][text]\" size=\"30\" type=\"text\" value=\"Great!\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_weight\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][weight]\" type=\"hidden\" value=\"3\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_response_class\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][response_class]\" type=\"hidden\" value=\"rate\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_id\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][id]\" type=\"hidden\">
</li>
<li data-weight=\"2\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_skeleton\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][skeleton]\" type=\"hidden\" value=\"true\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_text\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][text]\" size=\"30\" type=\"text\" value=\"OK\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_weight\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][weight]\" type=\"hidden\" value=\"2\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_response_class\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][response_class]\" type=\"hidden\" value=\"rate\">
<input id=\"survey_questions_attributes_0_answers_attributes_new_answers_id\" name=\"survey[questions_attributes][0][answers_attributes][new_answers][id]\" type=\"hidden\">
</li>
我试图用new_id
变量的内容替换new_answers
的所有实例。
当我运行该程序时,什么也无法替代。但是,如果我将$(this).html().replace(regexp,new_id);
包裹在alert()
或console.log()
中,则这些输出将显示new_answers
被应有的替换。
我不知道为什么会发生这种情况,而现在我的大脑却痛了。
解决方法
您需要将“ 11” HTML返还给该元素。试试这一行:
$(this).html($(this).html().replace(regexp,new_id));
詹姆士
, 您是否要尝试.replaceWith()
?我在jquery API中看不到“ 14”。
, var newHtml = $(this).html().replace(regexp,new_id);
$(this).html(newHtml);