jQuery 将生成的 HTML 存储在变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13845313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:00:24  来源:igfitidea点击:

Store generated HTML in variable

jqueryhtmlcode-generationinnerhtml

提问by user1721135

I have a simple jQuery table editor, and want to be able to store the whole table in a variable. Later the state of the table will be saved, sort of a mini CMS.

我有一个简单的 jQuery 表编辑器,并且希望能够将整个表存储在一个变量中。稍后表的状态将被保存,有点像迷你 CMS。

I tried using HTML, but it doesn't work for the generated elements.

我尝试使用 HTML,但它不适用于生成的元素。

What is the best way to to do this? Also, is what .html()returns safe, or should I not use it because of browser differences in innerHTML?

做到这一点的最佳方法是什么?另外,什么.html()返回安全,或者我不应该因为浏览器差异而使用它innerHTML

$("#target").click(function() {
    $('#myTable tr:last').after('<tr><td>Bla</td><td><div class="remove">REMOVE</div></td></tr>');
});

$("#myTable").on('click', '.remove', function(event) {
    $(this).parent().parent().remove();
});

var table = $("#myTable").html();
$("button").click(function() {
    $(".result").html(table);
});

回答by FixMaker

Try updating the click handler to the following:

尝试将点击处理程序更新为以下内容:

$("button").click(function() {
    var table = $("#myTable").html();
    $(".result").html(table);
});

See it working here: http://jsbin.com/ucopun/11

看到它在这里工作:http: //jsbin.com/ucopun/11

回答by Atif Mohammed Ameenuddin

Do you want to store the whole table in a different element or in a variable ?

您想将整个表存储在不同的元素中还是变量中?

If you want to store it in a variable then

如果要将其存储在变量中,则

$('button').on('click', function(){
    var table_html = '<table id="myTable">' + $('#myTable').html() + '</table>';
    // alert(table_html);
});

Fiddle - http://jsfiddle.net/84ETb/

小提琴 - http://jsfiddle.net/84ETb/

回答by BenM

Can't you just call html()after you've done your modifications (i.e. when the button is clicked, not when the DOM is ready)

您不能html()在完成修改后调用(即单击按钮时,而不是在 DOM 准备好时)

var the_content = $('#myTable').html();