Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 工作jQuery代码不在条件内部工作_Javascript_Jquery_Ruby On Rails_If Statement - Fatal编程技术网

Javascript 工作jQuery代码不在条件内部工作

Javascript 工作jQuery代码不在条件内部工作,javascript,jquery,ruby-on-rails,if-statement,Javascript,Jquery,Ruby On Rails,If Statement,我想设置一个元素内容,以防它为空 html.erb代码如下: <div class="comments-section"> <% if micropost.comments.any? %> <ol id="comments_micropost-<%= micropost.id %>"> <% micropost.comments.each do |comment| %> <%= render

我想设置一个元素内容,以防它为空
html.erb
代码如下:

<div class="comments-section">
  <% if micropost.comments.any? %>
    <ol id="comments_micropost-<%= micropost.id %>">
      <% micropost.comments.each do |comment| %>
        <%= render comment %>
      <% end %>
    </ol>
  <% end %>
</div>
案例2:micropost已经有注释(
micropost.comments.any?
为真):

var comments=$('ol#comments_microspost-');
注释。附加(“”);
这两段代码单独使用时都可以工作。但是,在下列条件下,与案例2一起插入时,案例1的代码不起作用:

if (comments == null) {
  $('#micropost-<%= @micropost.id %>').find('.comments-section').html("<%= escape_javascript(render partial: 'comments/comments') %>");
} 
else {
  comments.append('<%= escape_javascript(render partial: @comment) %>');
};
if(注释==null){
$(“#micropost-”).find(“.comments节”).html(“”);
} 
否则{
注释。附加(“”);
};
我不明白为什么
if(comments==null)
代码没有执行。我还尝试了
if(comments==undefined)
if(!comments)
,但没有任何改进

相反,将成功执行条件的
else
部分。

JavaScript将不存在的DOM元素视为长度为0的对象。可以通过使用web浏览器控制台、写入DOM元素并检查控制台输出来验证这一点。选择一个没有注释的micropost(比如带有
id=304
):
micropost.comments。任何?
都将为false,文档中不会出现
div.comments-section
中的所有内容。打开控制台并在提示下编写以下代码:

$('ol#comments_micropost-304');
输出将是:

  • []
    在基于铬的浏览器中
  • Object{length:0,prevObject:Object,context:HTMLDocument→ 选择器:Firefox中的“ol#comments_micropost-304”}

  • 原始的
    if
    语句不起作用,因为对象不为null且
    length=0
    。因此,正确的if语句是:
    if(comments.length==0)

    @Asarluhi if length大于0。比现有的多。如果长度为0,则它不可用。如何将长度表示为0:
    如果(comments.length==0)
    …您可以调试并打印
    注释的值吗?
    如果(comments.length==0)
    有效:)不能使用rails调试方法调试js。在你的chrome/firefox开发者控制台上试试这个<代码>风险值注释=$('ol#comments_micropost-1')其中1是micropost.id,看看你得到了什么
    if (comments == null) {
      $('#micropost-<%= @micropost.id %>').find('.comments-section').html("<%= escape_javascript(render partial: 'comments/comments') %>");
    } 
    else {
      comments.append('<%= escape_javascript(render partial: @comment) %>');
    };
    
    $('ol#comments_micropost-304');