0

私はJavascriptクラスを作成しています

クラスはこれ

(function(window){

    function Person(id,name,position,imageUrl){

    this.id = id;
    this.name = name;
    this.position = position;
    this.imageUrl = imageUrl;

    }

    Person.prototype.getPersonDiv = function(){

      var persondiv; 

    }

}(window));

このクラスを使用して、その場で div を作成しています。divの基本構造は次のようになります

<div id = "employee1" class = 'person-profile'>

 <div class = 'avatar'>
   <img src = ""/>
 </div>

 <div class = 'employee-details'>
   <p>this.id <br/> this.name <br/> this.position<p>   
 </div>

</div>

div id employee1 は、文字列 'employee' と id (クラスのプロパティ) を連結することによって作成されます。同様に、img url は imageUrl (クラスのプロパティ) から取得する必要があります。同様に、すべての従業員の詳細です。

私が計画しているのは、内部 HTML または追加として記述することです。文字列を正しく作ることができないようです。

文字列は getPersonDiv 関数の persondiv 変数に書き込まれ、関数を呼び出すと返されます。

4

2 に答える 2

2

ある種の JavaScript マイクロテンプレートを使用して、次のようなことを試すことができます。

(function(window){

    function Person(id,name,position,imageUrl){

    this.id = id;
    this.name = name;
    this.position = position;
    this.imageUrl = imageUrl;

    }

    Person.prototype.getPersonDiv = function(){
      var _this = this;

      /* create basic person template */
      var personTPL = "<div class = 'employee-details'>"
          + "<p>{id}<br/>{name}<br/>{position}<p></div>";

      /* change any placeholder with instance properties */
      return personTPL.replace(/\{([^}]+)\}/g, function(tpl, key) {
             return  _this[key] || "undefined"
          });  
    };


     var me = new Person("10", "Fabrizio", "javascriptmonkey", "http://...");

     /* return HTML */
     console.log(me.getPersonDiv());

     /** e.g.
      *
      * <div class = 'employee-details'><p>10<br/>
      * Fabrizio<br/>javascriptmonkey<p></div>  
      */
}(window));

フィドルの例: http://jsfiddle.net/6qZg5/

于 2012-04-27T12:50:40.283 に答える
1

このようなものをお探しですか?
その場合は、定義済みの html マークアップを個人データと連結して、その場で div を作成する必要があります。

Person.prototype.getPersonDiv = function(){
 return '<div id = "employee1" class = "person-profile"> <div class = "avatar"> <img src = "'+ this.imageUrl +'"/> </div> <div class = "employee-details"> <p>' + this.id + '<br/>' + this.name + ' <br/>' + this.position + '<p> </div> </div>'; 
}

いくつかの JavaScript テンプレート エンジンを確認することをお勧めします。john resig のマイクロ テンプレート エンジンを使用したデモを次に示します: http://jsfiddle.net/YHZBS/2/

それがうまくいくことを願っています。

于 2012-04-27T12:52:10.787 に答える