java - 使用 java javascript 脚本 API 操作 HTML 节点

标签 java javascript rhino nashorn java-scripting-engine

我正在使用Java Scripting API效果很好。现在我有一个函数,我想获取所有 <a>字符串中的标签,然后在返回操作的字符串之前添加/删除属性。问题当然是,我不能只使用 document.getElementsByTagName 。您是否想到了无需经历正则表达式 hell 的简单选择?

请注意,我目前正在 Java 7(使用 Rhino)上运行,计划更新到 Java 8(使用 Nashorn),因此我不想使用任何特定于 Rhino 的 API。

最佳答案

在 Addi Osmani 的《学习 JavaScript 设计模式》一书中,作者提到了类似问题的 3 种替代方案,显然 getElementById() 是最快的。

摘自书中:

Imagine that we have a script where for each DOM element found on page with class "foo," we wish to increment a counter. What's the most efficient way to query for this collection of elements? Well, there are a few different ways this problem could be tackled:

  • Select all of the elements in the page and then store references to them. Next, filter this collection and use regular expressions (or another means) to store only those with the class "foo."
  • Use a modern native browser feature such as querySelectorForAll() to select all of the elements with the class "foo."
  • Use a netive feature such as getElementsByClassName() to similarly...

另一种方法是,由于您使用的是 Nashorn/Rhino,因此您可以使用 Xerces 库的 Java 实现来操作 DOM。

希望这可以帮助您找到解决方案。

关于java - 使用 java javascript 脚本 API 操作 HTML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26465645/

相关文章:

java - 如何设计正确的 XML 并根据请求名称检索值?

java - 基本的多态/继承问题

javascript - Java 构建器模式可从 Rhino 中的 JavaScript 访问

java - Eclipse:自定义警告(Rhino 字符串参数)

java - 直接从 double 组组装 JTS 多边形?

javascript - 编译失败,在 webpack 上引导

javascript - 加载页面,在 JavaScript 警报时给出变量

javascript - Chrome 扩展程序中的 Firebase UI : signInSuccess never called

javascript - 在 Rhino 的服务器脚本中使用 jwt 生成 jsrsasign

java - org.springframework.web.servlet.PageNotFound noHandlerFound spring