2013-07-18 110 views
3

我已經在cljs文件下面的代碼:是否可以插入並運行動態腳本標記?

(def template 
    "<script type=\"text/javascript\"> 
     console.log(\"The script was run\"); 
    </script>") 

(defn add-script [] 
    (let [s (js/document.createElement "div")] 
    (set! (.-innerHTML s) template) 
    (js/document.head.appendChild (.-firstChild s)))) 

(顯然,真正的腳本模板的內容與此不同,但是這說明了什麼問題)

當我看的文檔中添加後腳本已經運行,果然,腳本模板已經插入到代碼中。問題是代碼並未實際執行。如果這只是js,我會簡單地評估模板。但是,Clojurescript沒有eval,所以我想我會嘗試使用腳本標籤動態添加JavaScript模板的內容。

我該如何得到這個工作,具體來說,我怎樣才能獲得我的腳本模板的這些內容來評估後,我已經動態地插入它?

+4

腳本不要跑,當你用'innerHTML'添加。你必須追加一個'腳本'節點。 – Barmar

回答

0
(def template 
    "<script type=\"text/javascript\"> 
     console.log(\"The script was run\"); 
    </script>") 

(defn add-script [] 
    (let [e (js/document.createElement "script") 
     t (subs template 32 (- (count template) 14))] 
    ;; t -> "  console.log(\"The script was run\");" 
    (set! (.-text e) t) 
    (js/document.head.appendChild e))) 

工程。其實我很驚訝這個innerHTML行爲導致代碼無法加載。看起來不一致,對我沒有多大意義。

我也很感激正確的Clojurescript正則表達式來抓取我的腳本標記中的內容。我似乎無法找到在cljs中實際使用正則表達式的工作示例。

1

我已經做了類似的事情,此代碼

(let [the-head js/document.head 
     the-script (.createElement js/document "script") 
     the-script-value "console.log(\"The script was run\");" 
     ] 
    ; if you need to load a js file 
    ;(set! (.-type the-script) "text/javascript") 
    ;(set! (.-src the-script) "url_file") 
    (set! (.-innerHTML the-script) the-script-value) 
    (.appendChild the-head the-script) 
) 

我希望它能幫助你

相關問題