簡體   English   中英

如何將javascript對象連接到函數內動態創建的html元素

[英]how to connect a javascript object to a dynamically created html element inside a function

我正在制作一個游戲,我想擁有一個“玩家” object ,並且我想在功能中做到這一點,但是我也想將該對象綁定到作為player顯示的圖像上。 我想要這個,因為我后來創建了怪物,並且我希望懸停與懸停具有類似的效果,但是要基於該object的屬性(即顯示其健康狀況)。 我當前的方法不使用.data() ,而是采用向后編碼,盡管現在可以正常使用,但是我無法使用此代碼擴展游戲,所以我想對其進行修復。

這是我的嘗試

function Player() {
    this.currentLocation = 0;
    printPlayer(this);
}

function printPlayer(p) {
    $("#" + p.currentLocation).html( "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
        "class='onTop displayCurrentHealth' alt='you' border='0' />" +
        "<div class = 'healthLost hide'></div>");
}
var player = new Player();
console.log($("#" + player.currentLocation).data("inFight", "false"));
console.log($("#" + player.currentLocation).data("inFight"));
console.log($("#" + player.currentLocation).data(!"inFight"));

這是我的console.log()結果

Object[]
adventure.js (line 62)
null
adventure.js (line 63)
null
adventure.js (line 64)

這是我的舊代碼

function Player(id) {
    this.id = id;
    this.healthid = this.id + "health";
    this.displayText = "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
        "class='onTop displayCurrentHealth' id='" + this.id + "' alt='you' border='0' />" +
        "<div id = '" + this.healthid + "' class = 'healthLost hide'></div>";
    this.inFight = false;
    this.currentLocation = 0;
    this.xp = 0;
    this.level = 1;
}

Object.defineProperty(player,"health",{ 
    set: function() { 
    return 100 + ( this.level * 150 );
    }, 
    get: function() { 
    return 100 + ( this.level * 150 );
    },
    enumerable: true  
} );

player.currentHealth = player.health;

Object.defineProperty(player,"strength",{ 
    set: function() { 
        return ( this.level * 5 );
    }, 
    get: function() { 
        return ( this.level * 5 );
    },
    enumerable: true 
} );

Object.defineProperty(player,"hitRating",{ 
    set: function() { 
        return 3 + ( this.level );
    }, 
    get: function() { 
        return 3 + ( this.level );
    },
    enumerable: true 
} );

如何在函數中動態地將它作為jquery data()創建到可以更改位置的圖像

--update--

我添加了這個

$("#" + player.currentLocation).data("foo");
console.log($("#" + player.currentLocation).data());

這也返回null

--update--

好的,所以我認為我需要某種mvc ,有沒有辦法在javascript / jquery中做到這一點? 如果是的話如何? 請提供完整的說明和/或鏈接。

不要將data()附加到任何DOM節點。 您應該有一個知道其DOM節點的對象,以及一個Model 您的怪物也可以訪問Model因此他們知道播放器還剩下多少生命值。

您很少需要使用data()來傳遞信息。 這將使保持您的應用程序更新變得更加困難,尤其是如果您以后想要調整DOM時。

保持DOM和業務邏輯盡可能獨立,以保持靈活性。

var Model = Function( id ) {
 this.health = 100;
 this.id = id;
};

// This object is showing examples of different ways an object can know about the image
var Monster = Function( hero_model, monster_model ) {
  this.sprite = $('#element').tmpl({}); // using jQuery template
  this.sprite = $('<img src="">'); // if you are making image based on model data
  this.sprite = $('#img-' + hero_model.id ); // if you wanted to  look on DOM then, based on data passed in
  this.sprite = document.getElementById( 'img-' + hero_model.id ); // to get element without jquery
};

var Player = Function( model ) {
 this.model = model;
}


// Passing 1 as ID, but you can have a number that increments
var hero_model = new Model( 1 );
hero_model.damage = 50;

var monster_model = new Model( 1 );
monster_model.damage = 10;

var hero = new Player( hero_model );

var monster = new Monster( hero_model, monster_model );

正如評論中指出的那樣,保留數據的關鍵是保留與其連接的DOM節點。

一種開始的方式可能看起來像這樣(從您的代碼開始,進行最小的更改):

function Player() {
    var self = this;

    self.location = 0;
    self.level = 1;
    self.xp = 0;
    self.inFight = false;

    // add methods that calculate XP and so on
}

function Game() {
    var self = this,
        player = new Player(),
        $playerSprite = $("<img>", {
            "class": "onTop displayCurrentHealth",
            "src": "http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png",
            "alt": "you"
        }).data("model", player);

    self.printPlayer = function () {
        $("#" + player.location).append($playerSprite);
    };

    // init
    self.printPlayer();
}

暫無
暫無

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

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