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

时间:2015-04-02 00:14:16

标签: javascript jquery dom-manipulation

我用DB从PHP动态生成行,一旦它编译初始页面代码看起来像这样:

<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的内容。例如,我需要使用类li(例如1,2,3,4)向Col_ID添加值,并且在删除时我需要再次修改内容。

我该如何处理content.getElement行?

1 个答案:

答案 0 :(得分:2)

如果您确实需要使用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