无法获得其他方法是否可以在 HAML JavaScript 中正常工作

Can't get if else to work right in HAML javascript

本文关键字:JavaScript 常工作 工作 HAML 其他 方法 是否      更新时间:2023-09-26

做一个小的演示迷你博客应用程序,有评论。与 ROR 和 HAML 合作。我希望使用 AJAX 创建注释,所以我写了 create.js.haml。我还希望在创建过程中出现任何错误。

创建.js.haml

:plain
if #{@comment.errors.any?} {
  $("#CommentError").html("#{escape_javascript(render(:partial => "error"))}");
  $("#CommentError").attr("style", "display: inline");
} else {
  $("#CommentsTable").append("#{escape_javascript(render(@comment))}");
  $("#CommentError").attr("style", "display: false");}

这行不通。条件的计算结果为 truefalse,但不执行代码。但是,如果我将条件的任何部分放在 create.js.haml 中,它就可以工作了。

这在出现错误的情况下有效:

:plain
  $("#CommentError").html("#{escape_javascript(render(:partial => "error"))}");
  $("#CommentError").attr("style", "display: inline");

如果没有错误并且我需要添加注释,这有效:

:plain
  $("#CommentsTable").append("#{escape_javascript(render(@comment))}");
  $("#CommentError").attr("style", "display: false");

这是观点,尽管我认为问题不存在:

%p
  %strong Title:
  = @post.title
%p
  %strong Text:
  = @post.text
%h3 Comments:
.CommentsArea
  = render @post.comments
#CommentError{:style => 'display: none'}  
%h2 Add a comment:
= render "comments/form"
= link_to 'Back', posts_path
|
= link_to 'Edit', edit_post_path(@post)

也许这会起作用(我现在无法自己检查)

- if @comment.errors.any?
  :plain
    $("#CommentError").html("#{escape_javascript(render(:partial => "error"))}");
    $("#CommentError").attr("visible", "true");
- else
  :plain
    $("#CommentsTable").append("#{escape_javascript(render(@comment))}");
    $("#CommentError").attr("visible", "false");

我认为你在这里混合Ruby和Javascript有点太多了。 试试这个。

if @comment.errors.any?
  :javascript
    $("#CommentError").html("#{escape_javascript(render(:partial => "error"))}");
    $("#CommentError").attr("visible", "true");
else
  :javascript
    $("#CommentsTable").append("#{escape_javascript(render(@comment))}");
    $("#CommentError").attr("visible", "false");

有关更多文档:http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter