2

我有一个获取 div 的 HTML 的 var。我想在隐藏的表单字段中使用该 var,以便可以将 HTML 保存到数据库中。

我只是难以将 HTML 或 var 转换为字符串。目前,将 var 按原样添加到我的输入中会破坏代码。

我尝试过.wrap('<pre />');以几种不同的方式使用,但它没有帮助,我认为它不正确。

谁能指出我正确的方向?谢谢!

var code = $('#container').html();

code = code.wrap('<pre />')

document.write('<input type="hidden" name="html" value="' + code + '">');
4

2 回答 2

5

您最好使用辅助方法而不是直接document.writeas(因为它是 HTML),您需要对其进行转义(确保代码中没有引号)。长话短说,也许使用类似的东西:

$('<input>',{
  'type':'hidden',
  'name':'html'
}) // create element
  .val(code) // use helper to insert HTML (auto-excapes)
  .appendTo('body'); // insert it where ever you need it

进一步解释:比如说,code有以下内容:

<div class="foo">bar</div>

通过使用文档写入(而不是转义它),您正在编写:

<input type="hidden" name="html" value="<div class="foo">bar</div>">

class="foo"及其引号)会干扰原始隐藏元素的value=""属性。using.val()避免了这种情况,因为它确保将值安全地插入到元素中。

于 2013-01-02T01:45:27.997 回答
0

使用 jQuery,这可能是最好的方法......

jQuery(document).ready(
    function (){ 
        var code = jQuery.trim(jQuery('#container').html());
        jQuery("form").append('<input type="hidden" name="html" value="' + code + '">');
});
于 2013-01-02T02:30:48.620 回答