简体   繁体   English

使用jQuery加载html并重复使用以创建小部件(模板)

[英]Load html with jQuery and reuse for widget creation (templating)

Im trying to build some widgets and want to separate the html template from the widget definition. 我试图建立一些小部件,并希望将HTML模板与小部件定义分开。 Im new to jQuery and want to evaluate if we can use it for a small read only web application. 我是jQuery的新手,希望评估我们是否可以将其用于小型只读Web应用程序。 What I've down so far: 到目前为止,我所经历的是:

 $(function() { var load = function() { var div = $("<div>"); div.testwidget({imgUrl:"http://foo.com/bar.gif"}); $( "#root" ).append(div); }; var html; $.get("testwidget.html", function(data) { html = data; load(); }, "html"); $.widget("custom.testwidget", { _create: function() { var content = html; var photo = $(content).find(".photo"); photo.attr("src", "http://foo.com/bar.gif"); //photo.attr("src", function() {return this.imgUrl}); this.element.append(content); } }); }); 

In the file testwidget.html is a template like: 在文件testwidget.html中,有一个类似于以下内容的模板:

 <div> <div class="hit-image"> <img class="photo" /> </div> </div> 

It works to load the html and reuse it for the widget creation. 它可以加载html并将其重新用于小部件创建。 I dont know if that is good for performance but I think better than loading the html on every widget creation. 我不知道这是否对性能有好处,但我认为比在每个小部件创建中加载html更好。 What doesn't work is setting the src attribute on the img tag. 不起作用的是在img标签上设置src属性。 Its just not present after appending the widget. 附加小部件后,它不存在。 Can anyone tell me what Im doing wrong? 谁能告诉我我做错了什么?

Its just a proof of concept, but Im happy about tips how to improve my code structure. 它只是一个概念证明,但是我很高兴提供有关如何改善代码结构的技巧。

I don't see where you define the options within your widget. 我看不到您在窗口小部件中定义选项的位置。 I would expect something like: 我希望这样的事情:

$.widget("custom.testwidget", {
  options: {
    imgUrl: "http://foo.com/bar.gif"
  },
  _create: function() {
    $.get("testwidget.html", function(r){
      $(r).find(".photo").attr("src", this.options.imgUrl);
      this.element.append(r);
    });
  } 
});

Then, would use it like so: 然后,将其像这样使用:

var div = $("<div>")
    .appendTo("#root")
    .testwidget({ imgUrl: "http://foo.com/bar.gif" });
console.log("Loaded " + div.testwidget("imgUrl"));

Personally, I would just just make the template in the widget versus calling an external/alternate resource. 就个人而言,我只是在小部件中制作模板,而不是调用外部/备用资源。 Something like: 就像是:

$.widget("custom.testwidget", {
  options: {
    imgUrl: "http://foo.com/bar.gif"
  },
  _create: function() {
    var img = $("<img>", { class: "photo", src: this.options.imgUrl });
    var wrap = $("<div>", { class: "hit-image" });
    wrap.append(img);
    this.element.append(wrap);
  } 
});

Working Example: https://jsfiddle.net/Twisty/wv6kwzpf/ 工作示例: https : //jsfiddle.net/Twisty/wv6kwzpf/

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

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