现有的 HTMl 文档
<a href="http://google.com">Link</a>
喜欢将其转换为:
<a href="#" onclick="openFunction('http://google.com')">Link</a>
使用 JSoup Java 库可以完成许多花哨的解析。但是找不到像上述要求一样添加属性的线索。请帮忙。
最佳答案
要设置属性,请查看 the doc
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p><a href=\"http://google.com\">Link</a></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.getElementsByTag("a");
for (Element element : links) {
element.attr("onclick", "openFunction('"+element.attr("href")+"')");
element.attr("href", "#");
}
System.out.println(doc.html());
会改变:
<a href="http://google.com">
进入
<a href="#" onclick="openFunction('http://google.com')">Link</a>
关于java - JSoup - 将 onclick 函数添加到 anchor href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36237859/