2016-07-28 72 views
0

我想使用jQuery生成一些HTML,我想只創建具有所需的類等元素,然後將它們附加到對方,如果這是有道理的。我寫了下面的代碼,它不會產生任何錯誤,但也不會將HTML添加到容器中。使用jQuery生成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默,如顯示的console.log被沒有你認爲改變執行我的twitter_plugin功能, ,所以這不是問題

+0

你得到你的控制檯日誌? – Adjit

+0

你有沒有包含jQuery? – gaetanoM

回答

1

問題是,你有一個jQuery的IIFE,但在你有你的'$ .fn.twitter_插件函數'已定義但未調用。 在函數定義的末尾,您應該添加()來調用它。

所以

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

應該

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

    }(); 

我也不知道這[0]是完全可靠的,可能是更好的只是身體保存爲您的容器元素。這只是一個窗口對象,所以它沒有0索引元素

var container = $('body') 會解決你的問題。

+0

'this [0]'獲得從這裏定義的元素$(「#map_canvas」)。twitter_plugin({});'因爲我需要將新元素放在那裏,而不是放在主體中。並感謝我的問題的答案:) –

+0

請參閱編輯,missing()不能解決問題。 –

0

我犯的愚蠢的錯誤,代碼工作正常,我只是拼錯目標元素的ID,現在這個工作。