如何用jquery中的escape char替换html内容

时间:2012-07-26 19:25:26

标签: javascript jquery

我们需要用jquery替换部分html内容。

original_string = '<option value=\"\"><\/option>\n'
replacing_string = '<option value=""></option> <option value="11">2012/05/09</option> <option value="6">2012/07/03</option> '
$('#id').html().replace(original_string, replacing_string);

问题是原始字符串和替换字符串中都有一堆转义字符,并且html().replace无法执行。如何用转义字符替换字符串? 感谢。

基本上我们正在为页面动态添加一个空选择选项。根据用户输入,需要将选择选项插入到内容中并呈现给屏幕。 html操作在渲染之前发生。

更新:HTML内容(对不起,它是大量的)

<div id="invoice_against_lease" style="display: none;">
<a onclick="add_nest_fields(this, "invoice_items", "<div class=\"fields\">\n<div class=\"input select optional\"><label class=\"select optional\" for=\"invoice_invoice_items_attributes_new_invoice_items_lease_usage_record_id\">Record#:<\/label><select class=\"select optional\" id=\"invoice_invoice_items_attributes_new_invoice_items_lease_usage_record_id\" name=\"invoice[invoice_items_attributes][new_invoice_items][lease_usage_record_id]\"><option value=\"\"><\/option>\n<\/select><\/div>\n<input id=\"invoice_invoice_items_attributes_new_invoice_items__destroy\" name=\"invoice[invoice_items_attributes][new_invoice_items][_destroy]\" type=\"hidden\" value=\"false\" /><a href=\"#\" onclick=\"remove_nest_fields(this); return false;\">Delete<\/a>\n<\/div>\n"); return false;" href="#">Add Record</a>
</div>

1 个答案:

答案 0 :(得分:4)

如果$('#id')是对<select...的引用,那么您应该只需用$('#id').html(replacing_string);替换所有选项

编辑:

如果$('#id')是父div的id,则代码只会略有变化:

$('#id select').html(replacing_string);

(当然,除非您在该div中有多个选择,否则您必须提供更多详细信息,以便我们可以帮助您使用正确的选择器...)