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/