多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
# 设置属性的值 <div><h2>问题</h2> <p>在你解析一个Document之后可能想修改其中的某些属性值,然后再保存到磁盘或都输出到前台页面。</p> <h2>方法</h2> <p>可以使用属性设置方法 <code><a title="Set an attribute value on this element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#attr%28java.lang.String,%20java.lang.String%29">Element.attr(String key, String value)</a></code>, 和 <code><a title="Set an attribute on all matched elements." href="http://jsoup.org/apidocs/org/jsoup/select/Elements.html#attr%28java.lang.String,%20java.lang.String%29">Elements.attr(String key, String value)</a></code>.</p> <p>假如你需要修改一个元素的 <code>class</code> 属性,可以使用 <code><a title="Add a class name to this element's class attribute." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#addClass%28java.lang.String%29">Element.addClass(String className)</a></code> 和 <code><a title="Remove a class name from this element's class attribute." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#removeClass%28java.lang.String%29">Element.removeClass(String className)</a></code> 方法。</p> <p><code><a title="A list of Elements, with methods that act on every element in the list." href="http://jsoup.org/apidocs/org/jsoup/select/Elements.html">Elements</a></code> 提供了批量操作元素属性和class的方法,比如:要为div中的每一个a元素都添加一个 <code>rel="nofollow"</code> 可以使用如下方法:</p> <pre><code>doc.select("div.comments a").attr("rel", "nofollow"); </code></pre> <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>中的其它方法一样,<code>attr</code> 方法也是返回当 <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> (或在使用选择器是返回 <code><a title="A list of Elements, with methods that act on every element in the list." href="http://jsoup.org/apidocs/org/jsoup/select/Elements.html">Elements</a></code> 集合)。这样能够很方便使用方法连用的书写方式。比如:</p> <pre><code>doc.select("div.masthead").attr("title", "jsoup").addClass("round-box"); </code></pre><br></div>