簡體   English   中英

如何使用javascript構造函數創建一個html元素?

[英]how to create a html element using javascript constructor?

我理解javascript構造函數的基本思想

function Person(name){
  this.name = name
}

Person.prototype.sayhi = function(){
  return this.name+' says hi !!! '
}
var bob = new Person('bob')
bob.name // bob
bob.sayhi // bob says hi !!!

但是,如果我想在真正的webapp中創建一個專輯,服務器會發送一個json數據數組

like:[{'id':1,'album_name':'test','user':'user_id'}]

,每個數組項應該是一個專輯,現在我想用這個數組項構建這個專輯作為div元素 ,我該怎么做?

我想要這個的原因是,如果我可以將專輯構建為真正的div元素,那么我可以做到這一點

 Album.prototype.open = function(){
    //some action
 }
 album = new Album(jdata)

 album.click(function(){
    this.open()
 })

這是可能的,如何定義這個構造函數,我認為這可能與構造函數返回值有關,這真的讓我困惑!

您可以執行以下操作:

var i, data, Albom, albom;

Albom = function Albom(data) {
  var i,
      div = document.createElement('div');

  for(i in data) {
    div.setAttribute('data-'+i, data[i]);
  }

  div.innerHTML = data.album_name;

  for(i in this) {
    if(typeof this[i] === 'function') {
      div[i] = this[i].bind(div);
    } else {
      div[i] = this[i];
    }
  }

  return div;
};

Albom.prototype.open = function open() {
  alert(this.getAttribute('data-id'));
};

data = [
  {'id':1,'album_name':'test1','user':'user_id1'},
  {'id':2,'album_name':'test2','user':'user_id2'}
];

for(i in data) {
  albom = new Albom(data[i]);
  document.body.appendChild(albom);
}

現在new Albom(data)將生成具有來自提供的data對象的屬性的新DOM元素,並且將在所創建的元素內具有所有原型屬性和函數,這些元素將在此DOM元素的范圍內執行(因此您可以在該方法內部引用this內容) 。

例如,您將能夠調用albom.open()並彈出帶有文本2的警報。

您可以在http://jsbin.com/isepay/10/edit上看到工作示例

使用與對象鍵匹配的類創建一些模板文件,然后循環切換鍵並填充模板文件。 例如:

function Album (album) {
    this.template = $('#template').clone().removeAttr('id');
    this.album = album;
}

Album.prototype.html = function () {
    var i, val;
    for (i in this.album) {
      if (!this.album.hasOwnProperty(i)) {
        continue;
      }
      val = this.album[i];
      this.template.find("." + i).html(val);
    }
    console.log(this.template);
    return this.template;
}

var foo = new Album({
    title: 'Cheap Thrills',
    artist: 'Frank Zappa',
    genre: 'Rock and Roll'
});

$('#main').html(foo.html());

這是一種一刀切的嘗試,雖然它不能滿足所有需求。 您可以為此解決方案不符合您需求的情況設置條件或有什么用途。 例如,如果數據是圖像URL,則設置innerHTML不是很有用,因此您可以設置'src'屬性,或創建帶有SRC屬性的img標記。

模板文件可能如下所示:

<div class="album">
  <div class="user"></div>
  <span class="foo"></span>
  <textarea class="bar"></textarea>
</div>

這是一個快速的小提琴: http//jsfiddle.net/bxw7Z/

如果您不喜歡使用類的想法,請嘗試使用數據屬性

我認為你的做法是錯誤的。 您應該使用任何客戶端模板引擎呈現響應JSON對象(例如Handlebars.JS)。

然后定義構造函數和原型方法

function album(container){
    this.container=container
}

album.prototype.open=function() {
    container.show();
}

album.prototype.renderHTML=function(jdata) {
 //This is handlebar.js code

 template=$('#albumTemplate').text();
 compiledTemplate=Handlebars.compile(template);
 renderedTemplate=compiledTemplate(jdata);
 container.html(renderedTemplate);
}

完成此操作后,您已准備好專輯類並可以像這樣開始使用它

var container=document.getElementById('myalbum001'),
    album=new album(container);

container.on('click',function(e){
    album.render(jdata);  //You can get jdata by making AJAX call before this line
    album.open()  
}

我建議你快速瀏覽一下Handlebar.js

暫無
暫無

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

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