2016-09-18 71 views

回答

1

發現數據我最終使用HTML5 Data Attributes

我加入data-*屬性,像這樣一個div

<%= tag("div", class: 'hidden-user-information', data: { 
    intercom_app_id: ENV['INTERCOM_APP_ID'], 
    user_id: current_user.id, 
    user_name: current_user.profile.name, 
    user_email: current_user.email, 
    user_created_at: current_user.created_at.to_i 
    }) %> 

而且使用jQuery,我用這些訪問在我的javascript:從形式 $('div.hidden-user-information').data('intercom-app-id');

3
  • 保持你的JavaScript文件在app /資產/ JavaScript的文件夾

  • 在視圖文件,使用隱藏字段中的數據要傳遞給JavaScript

  • 在你的JavaScript文件通過使用 $("#name_of_hidden_field")

+0

隱藏字段?我不想在我的應用中嵌入表單:/ – amingilani

+0

爲什麼不呢?它沒有做任何事,只是坐在那裏。 @amingilani提供了關於相同的解決方案,除了'data'屬性。 –

+0

@AlexanderLozada形式意味着輸入。恕我直言,數據屬性是一個更加優雅的方式來處理它。雖然,規範的方式是將數據放在body標籤中,但使用'tag_helper'更具可讀性。 – amingilani

相關問題