簡體   English   中英

使用jQuery生成HTML

[英]Generate HTML using jQuery

我正在嘗試使用jQuery生成一些HTML,我只想用所需的類等創建元素,然后在有意義的情況下將它們彼此附加。 我已經編寫了以下代碼,它不會產生任何錯誤,但是也根本不會將HTML添加到容器中。

怎么了?

(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));

像這樣執行:

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

編輯1

@Sean Reimer,我的twitter_plugin函數在沒有您建議的更改的情況下被執行,因為顯示了console.log,所以這不是問題

問題是您有一個用於jQuery的IIFE,但在其中定義了“ $ .fn.twitter_plugin函數”,但未調用它。 在函數定義的末尾,您還應該添加()來調用它。

所以

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

應該

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

  }();

我也不確定this [0]是否完全可靠,最好僅將主體保存為您的容器元素。 這只是一個窗口對象,因此它沒有0的索引元素

var container = $('body')將解決您的問題。

我犯了一個愚蠢的錯誤,代碼可以正常工作,我只是誤輸入了目標元素的ID,現在可以正常工作了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM