【问题标题】:How to replace html content with escape char in jquery如何在jquery中用转义字符替换html内容
【发布时间】:2012-07-26 19:25:25
【问题描述】:

我们需要用 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>

【问题讨论】:

  • 您没有通过var yourOption = $("option"); 构建元素的选项吗?
  • 不太清楚你在这里要做什么。您是在尝试操作字符串内容还是实际操作 DOM 中的 HTML?
  • 不确定它是否相关(可能只是复制粘贴错误),但您在前两行代码的末尾缺少一些分号...
  • 如果您想用另一个元素替换一个元素,请选择要替换的元素并使用.replaceWith,这比尝试匹配精确的html要容易得多
  • 我们需要替换元素的部分html内容。我们想用一个选项列表替换一个空的选择选项。

标签: javascript jquery


【解决方案1】:

如果$('#id') 是对您的&lt;select... 的引用,那么您应该能够简单地将所有选项替换为$('#id').html(replacing_string);

编辑:

如果$('#id')是父div的id,那么代码只是略有改动:

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

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

【讨论】:

  • 否,#id 不是选择元素的引用。整个内容都在一个 div 中,是一个动态添加的选择选项和标签。我们想插入一个选择选项并替换空的。
  • @user938363 在执行此操作时添加 HTML 的快照,这应该会有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2013-12-07
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
相关资源
最近更新 更多