简体   繁体   English

如何在jQuery中用转义字符替换HTML内容

[英]How to replace html content with escape char in jquery

We need to replace portion of the html content with 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);

The problem is that there are bunch of escape chars in both original and replacing string and the html().replace can not be executed. 问题在于,原始字符串和替换字符串中都有许多转义字符,并且无法执行html().replace How to replace a string with escape characters? 如何用转义字符替换字符串? Thanks. 谢谢。

Basically we are dynamically adding an empty select option to the page. 基本上,我们是在页面上动态添加一个空的选择选项。 Based on user input, a select options need to be inserted into the content and be rendered to the screen. 根据用户输入,需要将选择选项插入到内容中并呈现到屏幕上。 The html manipulation happens before rendering. html操作在渲染之前发生。

UPDATE: html content(sorry, it is massy) 更新: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>

If $('#id') is a reference to your <select... then you should be able to simply replace all of your options with $('#id').html(replacing_string); 如果$('#id')是对<select...的引用,那么您应该可以简单地将所有选项替换为$('#id').html(replacing_string);

EDIT: 编辑:

If $('#id') is the id of the parent div, then the code only slightly changes : 如果$('#id')是父div的ID,则代码只会稍有变化:

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

( unless, of course, you have more than one select in that div, then you'd have to provide more detail so that we can help you with the correct selector... ) (当然,除非您在该div中有多个选择,否则您必须提供更多详细信息,以便我们为您提供正确的选择器...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM