简体   繁体   English

在Scala.js中,如何切换类中元素的可见性?

[英]In Scala.js, how do I toggle visibility of elements in a class?

In a Scala.js program, I want to toggle the visibility of all elements on the HTML page in the class "my-img". 在一个Scala.js程序中,我想切换“ my-img”类中HTML页面上所有元素的可见性。 What I have so far is 我到目前为止所拥有的是

import org.scalajs.dom
import dom.document

val elems: dom.NodeList = document.getElemsByClassName("my-img")
for (i <- 0 until elems.length) {
   val e: dom.Node = elems(i)
   e.style.display = "none"  <-- this chokes, says style is not a member of Node

At this point I am trying to access the style member of a Node, which according to the Javascript docs should be there, but Scala.js is giving me an error. 此时,我正在尝试访问Node的样式成员,根据Javascript文档,该成员应该存在,但是Scala.js给我一个错误。

(Note that this is more a Javascript question than a Scala.js one per se.) (请注意,这本身不是Scala.js,而是一个Javascript问题。)

There are a few answers, depending whether you're willing to include the jQuery library. 有几个答案,这取决于您是否愿意包括jQuery库。 This is a somewhat heavy but extremely common library in the Javascript world, which is also often used in Scala.js programming. 在Javascript世界中,这是一个有点沉重但极其常见的库,它也经常在Scala.js编程中使用。 It isn't required, but it makes this sort of thing considerably easier. 它不是必需的,但是它使这种事情变得相当容易。

There are two popular Scala.js "facades" (Scala descriptions) for this library; 该库有两个流行的Scala.js“外观”(Scala描述)。 I wrote one of them, jquery-facade . 我写了其中之一jquery-facade If you pull that in (as described on that page), the problem becomes fairly trivial: 如果您将其拉入(如该页中所述),问题将变得很简单:

import org.querki.jquery._

// Fetch all of the nodes. jQuery uses CSS selectors, more or less,
// so this means "everything with class my-img".
val myImgs = $(".my-img")
// Hide all of them. myImgs is a JQuery object -- a wrapper around
// all of those nodes -- so a single call hides all of them:
myImgs.hide()
// Or show them:
myImgs.show()

That's untested (and I'm battling flu today, so please forgive me any errors), but I think it should work... 这未经测试(并且我今天正在与流感作斗争,所以请原谅我任何错误),但是我认为它应该可以工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM