因此,我正在爲ActiveAdmin表單構建一些Markdown助手。到目前爲止,我只有一個斜體。Javascript無法在active_admin內運行
#form.html.erb
# ... some form code
<%= link_to "i", "#", :class => "btn", :id => "italics_button" %>
<%= f.input :body %>
# ... rest of form omitted
這使我的按鈕,「italics_button」的ID,並與post_body的ID的textarea的。到目前爲止,一切都很好。
現在我有一個coffeescript文件來處理給定標籤中所選文本的包裝。
#posts.js.coffee
wrapText = (elementID, openTag, closeTag) ->
textArea = $("##{elementID}") #select the text area
len = textArea.val().length #total length of the text area
start = textArea[0].selectionStart # start of the selected text
end = textArea[0].selectionEnd # end of the selected text
selectedText = textArea.val().substring(start, end) # The selected Text
replacement = openTag + selectedText + closeTag # string with the selected text wrapped in the bbcode
textArea.val(textArea.val().substring(0,start) + replacement + textArea.val().substring(end, len)) # perform the replacement
$('#italics_button').click (event) ->
event.preventDefault()
wrapText('post_body', '*', '*')
我相當有信心,這個代碼是好的,因爲我撕開它的一個項目,從一兩個月前,我做了一個正常的非AA形式同樣的事情。
我已經更新了初始化的自定義JavaScript帶來:
# active_admin.rb
# rest of file omitted
config.register_javascript 'posts.js.coffee'
最後,我可以在Active管理新後的網頁上看到,JavaScript文件包含和編譯。
但是,javascript事件似乎沒有被調用。當我點擊#italics_button時,頁面會嘗試按照「#」鏈接進行操作,並且JavaScript不會運行。
啊我明白了。在我的另一個應用程序中,腳本被加載到底部,所以元素已經存在,但在這種情況下,AA在渲染任何東西之前將它加載到頂部。 – DVG
@DVG:對。無論如何,使用'$ - >'來包裝你的初始化東西是一個好主意,這樣你就不必擔心你的(Java | Coffee)腳本在頁面中的位置。 –