jQuery 使用 .html() 选择后编辑 innerHTML

jQuery Editing innerHTML after selecting it with .html()

我正在使用 PHP 从 DB 动态生成行,一旦编译初始页面代码如下所示:

片段

<div class="options" id="options">
        <div class="left_wrap">
            <ul>
                <li class="col_id b-bottom"></li>
                <li class="hazard_header"><h3>Hazard</h3></li>
                <li class="hazard_input b-bottom"></li>
                <li class="con_header b-bottom"><h3>Controls</h3></li>
                <li class="cat_header"><h3>Consequence Category</h3></li>
                <li class="cat_options"></li>
            </ul>
        </div>
        <div class="right_wrap">
            <h2>Inherent Risk (Assessed risk without controls)</h2>
            <ul class="fields">
                <li class="bg b-top b-right"><h3>Consequence Level</h3><br/><span class="con_level_val"></span></li>
                <li class="b-top b-right"><h3>Probability</h3><br/>Possible</li>
                <li class="bg b-top b-right"><h3>Exposure (frequency)</h3><br/></li>

页面加载后,我抓取包装内容 options

jQuery 片段:

content = $("div.options").html();

其中依次将上述代码存储在变量content中。现在,我的问题是如何编辑变量 content 的内容。例如,我需要使用 class Col_IDli 添加值,例如 1,2,3,4,当我删除时,我需要再次修改内容。

我怎样才能按照 content.getElement 的方式做一些事情?

如果您确实需要使用 HTML 字符串,您可以执行以下操作:

content = $("div.options").html();
var $content = $(content);
// now $content is a jQuery object with a bunch of (detached) elements
// you can use the common functions on it without problems, such as
$content.find("li.col_id").text("Some text");

// now you need to do something with $content, or everything you did will...
// ...be lost. You cold, for instance, update the other variable back:
content = $content.html();
// content now has the updated HTML

现在,如果您根本不需要 HTML 字符串,那么您可以直接像这样工作:

content = $("div.options");
content.find("li.col_id").text("Some text");
// now the DOM was already updated as you are dealing with attached elements