javascript - Rails View 中的文本区域在 js 中返回 null

标签 javascript jquery ruby-on-rails-4 codemirror

Rails 4。我有一个 View ,其中包含以下代码,我在文本区域中输入输入,并希望将代码镜像模式应用于文本区域2的代码。不幸的是,我无法读取文本的内容区域 1。即使我将代码粘贴到文本区域 1 并点击提交按钮,当我在 JS 文件中收到它时,它始终为空。

类别/show.html.erb:

<div id="ccontainer">
<div class="hero-spacer">
  <%= text_area_tag :cols => "30", :rows => "10", :id => "myText", :class => "editor1-pane" %> 
  <%= text_area_tag :cols => "30", :rows => "10", :id => "myText2", :class => "editor2-pane" %>  

  <%= button_to_function "✓", '$(this).toggleClass("buttonGrey buttonGreen");', :class => "buttonGrey" %>
 </div>

 </div>

categories.js 有:

$(document).ready(function () {

   $(".buttonGrey").on("click", function() {

       alert("Confirmed"+ $('#myText')); <--- Always returning null
       console.log($('.editor1-pane'));
       if(document.getElementById("myText").value == null){
           alert('NULL >>');
         }
       var myCodeMirror = CodeMirror.fromTextArea(document.getElementById('myText'), {
            lineNumbers: true,
            matchBrackers: true,
            styleActiveLine: true,
            theme: "eclipse",
            mode: { name: "xml", htmlMode: true }
         }
       );
     // do something
       document.getElementById("myText2").value = myCodeMirror.getValue();
   }) 
 });

我不知道我做错了什么!

最佳答案

Rails 期望 text_area_tag 后跟 名称、内容、选项,但您刚刚提供了选项。

因此,Rails 不是将“myText”指定为 id,而是将整个选项列表指定为 name(检查 HTML 输出以查看这一点),并且不设置任何选项。因此,您的 jQuery 选择器找不到任何内容。

试试这个:

<%= text_area_tag "myText", nil, :cols => "30", :rows => "10", :class => "editor1-pane" %>

这应该将文本区域的 ID 和名称设置为“myText”,并正确设置您的选项。

关于javascript - Rails View 中的文本区域在 js 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27214363/

相关文章:

javascript - 使用 javascript 在 <a href> 上应用类

javascript - ReactJS - setState 不是一个函数

javascript - 重构 if 语句 JavaScript

javascript - 使用 AJAX 加载 Google Maps API...但多个实例仅加载一次

php - jQuery/ajax/php 返回值

mysql - Rails 4 中 'users' 中的未知列 'where clause'

html - 仅在移动版本中,两个容器的相同 CSS 间距渲染不同

javascript - 如何定位所有输入文本和密码值?

javascript - 完成ajax调用后继续在js程序中

ruby-on-rails - Rails 4 gmaps4rails - 如何在 gmaps4rails gem 的标记信息窗口中包含指向 "show" View 的链接