简体   繁体   中英

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. I have written the below code, it doesn't produce any errors but also isn't adding the HTML to container at all.

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

@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

The problem is that you have an IIFE for jquery, but within you have your '$.fn.twitter_plugin function' defined but not called. 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 is just a window object, so it doesn't have a 0 index element

var container = $('body') would solve your problems.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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