我有一个向量:
(def my-collection ["image1.jpg" "image2.jpg" "image3.jpg"])
我想在文档中制作 3 张图像。
(println (count my-collection)) ; this prints count of my collection. This is 3.
(map (fn [x] (println x)) my-collection) ; doesn't do anything!
但是!
(def image-element (.createElement js/document "img"))
(def insert-into-body (.appendChild (.-body js/document) image-element))
(set! (.-src image-element) "image1.jpg")
这段代码非常适合一个元素!
我应该为收藏做什么?
最佳答案
map
函数用于通过应用指定的函数将一个集合转换为另一个集合。由于 (println x)
返回 nil
,因此代码的结果将是 (nil, nil, nil)
并带有副作用(每个图像名称打印在您的控制台中)。
也许您想定义一个函数来创建具有指定 src 的图像元素。
(defn create-image [src]
(let [img (.createElement js/document "img")]
(set! (.-src img) src)
img))
现在,您可以提供集合将图像名称映射到图像元素,然后将它们附加到 body 元素中。
(doseq [i (map create-image my-collection)]
(.appendChild (.-body js/document) i))
关于javascript - ClojureScript 中的向量到元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434643/