我将使用owasp-java-html-sanitizer,并尝试为我的HTML代码中的每个h2标签添加id属性,该属性应在多个页面加载之间保持不变,但对于页面上的每个元素都是唯一的(如id属性定义)。我尝试计算所有元素以获取索引,并将索引添加到每个h2元素中。但是,在Java中的此时点我无法访问此数据。然后我使用了UUID.randomUUID(),但由于它是随机的,因此id不是持久的。
以下是我当前拥有的代码:
以下是我当前拥有的代码:
public PolicyFactory HtmlPolicy() {
return new HtmlPolicyBuilder()
.allowElements("h3", "h4", "h5", "h6", "p", "span", "br", "b", "strong", "i", "em", "u", "hr", "ol", "ul", "li",
"img", "table", "tr", "th", "td", "thead", "tbody", "tfoot", "caption", "colgroup", "col", "blockquote", "figure", "figcaption", "object", "iframe")
.allowElements(
(String elementName, List<String> attrs) -> {
String uniqueID = UUID.randomUUID().toString();
// Add an attribute.
attrs.add("id");
attrs.add("headline-" + uniqueID);
attrs.add("class");
attrs.add("scrollspy");
// Return elementName to include, null to drop.
return elementName;
}, "h2")
.toFactory();
}
在JavaScript中,我会这样做:
$('h2').each(function(index, obj) {
let newObj = $(obj)[0];
$(newObj).attr('id', `headline-2-${index + 1}`);
});
有没有一种方法可以在这种情况下将每个 h2 元素的值增加 1?
h2:nth-of-type(index)
来在客户端上定位 H2。 - Christoph Dahlenattrs
的值并使用它来构建唯一的id吗? - morganney