ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
# 设置一个元素的HTML内容 <div> <h1><span style="font-size: 14px; line-height: 1.5;"></span></h1></div><b style="background-color: rgb(255, 255, 255); font-size: 21px;">问题</b><div><h1><span style="font-size: 14px; line-height: 1.5;"></span></h1> <p>你需要一个元素中的HTML内容</p> <h2>方法</h2> <p>可以使用<code><a title="A HTML element consists of a tag name, attributes, and child nodes (including text nodes and other elements)." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html">Element</a></code>中的HTML设置方法具体如下:</p> <pre><code>Element div = doc.select("div").first(); // &lt;div&gt;&lt;/div&gt; div.html("&lt;p&gt;lorem ipsum&lt;/p&gt;"); // &lt;div&gt;&lt;p&gt;lorem ipsum&lt;/p&gt;&lt;/div&gt; div.prepend("&lt;p&gt;First&lt;/p&gt;");//在div前添加html内容 div.append("&lt;p&gt;Last&lt;/p&gt;");//在div之后添加html内容 // 添完后的结果: &lt;div&gt;&lt;p&gt;First&lt;/p&gt;&lt;p&gt;lorem ipsum&lt;/p&gt;&lt;p&gt;Last&lt;/p&gt;&lt;/div&gt; Element span = doc.select("span").first(); // &lt;span&gt;One&lt;/span&gt; span.wrap("&lt;li&gt;&lt;a href='http://example.com/'&gt;&lt;/a&gt;&lt;/li&gt;"); // 添完后的结果: &lt;li&gt;&lt;a href="http://example.com"&gt;&lt;span&gt;One&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; </code></pre> <h2>说明</h2> <ul> <li><code><a title="Set this element's inner HTML." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#html%28java.lang.String%29">Element.html(String html)</a></code> 这个方法将先清除元素中的HTML内容,然后用传入的HTML代替。</li> <li><code><a title="Add inner HTML into this element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#prepend%28java.lang.String%29">Element.prepend(String first)</a></code> 和 <code><a title="Add inner HTML to this element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#append%28java.lang.String%29">Element.append(String last)</a></code> 方法用于在分别在元素内部HTML的前面和后面添加HTML内容</li> <li><code><a title="Wrap the supplied HTML around this element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#wrap%28java.lang.String%29">Element.wrap(String around)</a></code> 对元素包裹一个外部HTML内容。</li> </ul> <h2>参见</h2> <p>可以查看API参考文档中 <code><a title="Create a new element by tag name, and add it as the first child." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#prependElement%28java.lang.String%29">Element.prependElement(String tag)</a></code>和<code><a title="Create a new element by tag name, and add it as the last child." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#appendElement%28java.lang.String%29">Element.appendElement(String tag)</a></code> 方法来创建新的元素并作为文档的子元素插入其中。</p></div>