我正在尝试使用 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 容器 = $('body')
会解决你的问题。
关于javascript - 使用 jQuery 生成 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642455/