Clojure 使用嵌套向量发送数据以运行和使用项目

Clojure sending data with nested vector to function and use the items

首先,如果我的问题很简单或不清楚,我很抱歉。我几乎是 Clojure 的新手,我需要帮助。

我想创建一个函数来为菜单生成一些 HTML link。这就是我现在所拥有的,并且可以正常工作:

(defn test-function [title-id title-name]
    [:span {:onclick #(.scrollIntoView (.getElementById js/document title-id))
            :style {:color :red} title-name])


[:li (test-function "title-1-id" "title-1-name")]
[:li (test-function "title-2-id" "title-2-name")]

但是因为我有很多 li 标签,我想有这样的东西发送给函数,函数可以为我生成 links ,就像当前代码为我做的一样。但我还没有找到如何做到这一点,也不知道我是否应该使用矢量或其他东西。

[["title-1-id" "title-1-name"] ["title-2-id" "title-2-name"]]

提前谢谢你。

您可以使用 for, then destructure each element into id and name (I just renamed name to li-name to avoid shadowing function name) 并将整个 for 包裹在 [:ul ... ]:

[:ul
             (for [[li-id li-name] [["id1" "Scroll to red"] ["id2" "Scroll to pink"]]]
                  [:li {:style {:cursor :pointer
                                :color :red}
                        :on-click #(.scrollIntoView (.getElementById js/document li-id))}
                   li-name])]

[:div
             [:div [:img#id1 {:src "" :style {:width 600 :height 1000 :background "red"}}]]
             [:div [:img#id2 {:src "" :style {:width 600 :height 1000 :background "pink"}}]]
             [:div [:img#id3 {:src "" :style {:width 600 :height 1000 :background "yellow"}}]]]

请注意,您甚至不需要 Javascript 滚动到目标元素 - [:a ... ] 可以指向同一页面上的对象:

[:ul
             (for [[li-id li-name] [["id1" "Scroll to red"] ["id2" "Scroll to pink"]]]
                  [:a {:href  (str "#" li-id)
                       :style {:color           :red
                               :cursor          :pointer
                               :text-decoration :none}}
                   [:li li-name]])]
            [:div
             [:div [:img#id1 {:src "" :style {:width 600 :height 1000 :background "red"}}]]
             [:div [:img#id2 {:src "" :style {:width 600 :height 1000 :background "pink"}}]]
             [:div [:img#id3 {:src "" :style {:width 600 :height 1000 :background "yellow"}}]]]