0

我看到了一些似乎可以生成 HTML 的 Scala 代码...

  def pagePlay: TypedTag[dom.raw.HTMLElement] = div{
    val levels = Array(
      (10, "Easy game; you are allowed 10 misses."),
      (5, "Medium game; you are allowed 5 misses."),
      (3, "Hard game; you are allowed 3 misses.")
    )
    div(
      p("Inspired from ")(a(href:="http://www.yiiframework.com/demos/hangman/", target:="_blank","Yii's demo")),
      p("This is the game of Hangman. You must guess a word, a letter at a time.\n" +
        "If you make too many mistakes, you lose the game!"),
      form(id := "playForm")(
        for((level,text) <- levels) yield {
          val levelId = s"level_${level}"
          div(`class`:="radio")(
            input(id:=levelId, `type`:="radio", name:="level", onclick:={ ()=>
              Model.level() = level
            }, {if(level == Model.level()) checked:="checked"}),
            label(`for`:=levelId, style:="padding-left: 5px")(text)
          )
        }, br,
        input(`type`:="button", value:="Play!", `class`:="btn btn-primary", onclick:={ () =>
          if(Model.level() > 0) {
            Model.start()
            goto(pageGuess)
          }else{
            dom.alert("Please select level!")
          }
        })
      )
    )
  }

^ 这个 ScalaTag 代码实际上生成的 HTML 是可以被没有 javascript 支持的简单网络爬虫读取的,还是生成的 Javascript 正在修改 DOM 以生成 div 和段落等等?

我尝试阅读文档,但对于 div 和 p 来说,只有“模式:div:Tags.this.ConcreteHtmlTag[html.Div]”

4

1 回答 1

3

它同时使用两者,至少现在是这样:

从文档:

Although Scalatags was originally a HTML-String generation library, it now
ships with an additional backend that runs only on ScalaJS.

此外:

DOM 后端在所有 Scalatags 片段上提供了一个额外的方法 .render ,它将片段转换为 DOM 树:

val elem = div.render
assert(elem.children.length == 0)
elem.appendChild(p(1, "wtf", "bbq").render)
assert(elem.children.length == 1)
val pElem = elem.children(0).asInstanceOf[Paragraph]
assert(pElem.childNodes.length == 3)
assert(pElem.textContent == "1wtfbbq")
As you can see, you can manipulate DOM elements directly, calling standard DOM APIs like .children, .appendChild, etc.

如您所见,您可以直接操作 DOM 元素,调用标准 DOM API,如 .children、.appendChild 等。如您所知,这就是 Javascript!

于 2016-04-05T05:09:14.267 回答