如何在clojure Hiccup中嵌入javascript?

时间:2017-07-05 17:23:38

标签: javascript html clojure clojurescript hiccup

我正在使用Hiccup(和其他东西)在clojure中编写一个Web服务器应用程序。 我尝试启用复选框并禁用两个下拉字段,但是我无法使其工作。

[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]

2 个答案:

答案 0 :(得分:1)

on-change是一个React处理程序,不能在服务器端HTML中工作。

如果您不想创建单独的JS文件,可以使用onclick attribute:以下内容应该有效(假设hf/check-box函数创建了一个元素具有给定属性):

[:td (hf/check-box
      {:onclick (str "toggleText(" (name endtag) ","
                     (name tytag) "," (name tmtag) ")")}
      endtag)]

答案 1 :(得分:0)

感谢Aleph,你的修复和为函数中的cb参数添加getElementById一起做了伎俩!

该功能现在看起来像这样

[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !document.getElementById(cb).checked;
    document.getElementById(t2).disabled = !document.getElementById(cb).checked;}"]

我也简化了Hiccup代码(不将标签作为参数传递),所以看起来像这样

[:td (hf/check-box {:onclick (str "toggleText('endtag','toyear','tomonth')")} :endtag (some? (:toyear m)))]
[:td (hf/drop-down :toyear (range 2013 2031))]
[:td (hf/drop-down :tomonth (range 1 13))]