简体   繁体   English

JavaScript 创建元素

[英]JavaScript createElement

After the user has posted an article (AJAX), I want the article to update though AJAX.用户发布article (AJAX) 后,我希望文章通过 AJAX 更新。

The issue, however, is when there are no articles and the user creates the first one -- that means I need to create the article-div with all the logic within it (eg. loop).然而,问题是当没有文章并且用户创建第一个时——这意味着我需要创建包含所有逻辑的article-div (例如循环)。

I know how to create a simple element in JS, but how does one create something like this?我知道如何在 JS 中创建一个简单的元素,但是如何创建这样的东西呢?

welcome#index

#article-div
    - @articles.each do |article|
        .ajax_load.article-content{ id: "article" }

articles/create.js.erb

if (!($('#article-div'))) {
    $('#article-div').append('<%= j render(@article) %>');
}

You have to check the length of that jquery object,你必须检查那个 jquery 对象的length

if (!$('.article-content').length) {

Since a jquery object never be evaluated to false .由于 jquery 对象永远不会被评估为false And there is no need to invoke .remove() over an empty jquery object.并且不需要在空的 jquery 对象上调用.remove() You full code would be,你的完整代码是,

if (!$('.article-content').length) {
   $('#article-div').append('<%= j render(@article) %>');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM