简体   繁体   English

使用jQuery生成HTML

[英]Generate HTML using jQuery

i'm trying to generate some HTML using jQuery, I want to just create the elements with the required classes etc, and then append them to each other if that makes sense. 我正在尝试使用jQuery生成一些HTML,我只想用所需的类等创建元素,然后在有意义的情况下将它们彼此附加。 I have written the below code, it doesn't produce any errors but also isn't adding the HTML to container at all. 我已经编写了以下代码,它不会产生任何错误,但是也根本不会将HTML添加到容器中。

What's wrong? 怎么了?

(function($) {
    $.fn.twitter_plugin = function( options ) {

    var container = this[0];

    console.log('Started');
    // Make aJax call

    // Generate HTML
    $con = $("<div>", { "class" : "tweet" });
    $(container).append($con);
      $col1 = $("<div>", { "class" : "twocol" });
      $con.append($col1);
      $col2 = $("<div>", { "class" : "tencol last" });
      $con.append($col2);

        // Profile Image
        $tweet_profile_div = $("<div>", { "class" : "tweet-profile-photo" });
        $col1.append($tweet_profile_div);
          $profile_img = $("img", { "src" : '', "class" : "responsive-img" });
          $tweet_profile_div.append($profile_img);
        // END Profile Image

      // Tweet
      $tweet_head = $("div", { "class" : "tweet-head" });
      // END Tweet

  };
}(jQuery));

Executing this like so: 像这样执行:

<script src="js-src/themev2/twitter_plugin.js"></script>
<script>
$( document ).ready(function() {
    $("#map_canvas").twitter_plugin({ });
});
</script>

Edit 1 编辑1

@Sean Reimer, my twitter_plugin function is being executed without that change you suggested, as the console.log is displayed, so this isn't the issue @Sean Reimer,我的twitter_plugin函数在没有您建议的更改的情况下被执行,因为显示了console.log,所以这不是问题

The problem is that you have an IIFE for jquery, but within you have your '$.fn.twitter_plugin function' defined but not called. 问题是您有一个用于jQuery的IIFE,但在其中定义了“ $ .fn.twitter_plugin函数”,但未调用它。 At the end of your function definition you should add () to invoke it as well. 在函数定义的末尾,您还应该添加()来调用它。

so 所以

      $tweet_head = $("div", { "class" : "tweet-head" });
      // END Tweet
  };

should be 应该

      $tweet_head = $("div", { "class" : "tweet-head" });
      // END Tweet

  }();

I also am not sure if this[0] is entirely reliable it might be better to just save the body as your container element. 我也不确定this [0]是否完全可靠,最好仅将主体保存为您的容器元素。 This is just a window object, so it doesn't have a 0 index element 这只是一个窗口对象,因此它没有0的索引元素

var container = $('body') would solve your problems. var container = $('body')将解决您的问题。

我犯了一个愚蠢的错误,代码可以正常工作,我只是误输入了目标元素的ID,现在可以正常工作了。

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

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