【问题标题】:HTML String on Object Property Won't Update对象属性上的 HTML 字符串不会更新
【发布时间】:2019-02-04 15:26:16
【问题描述】:

我有一个对象构造函数,它设置一些属性,然后使用它们连接一个字符串以写入 DOM。我可以看到这在某些情况下有效,但在其他情况下无效。

function Fighter(name, level, attackPts, defencePts, imgSource) {

        // TRUNCATED PROPERTY ASSIGNMENTS AREA:
        this.attackPts = attackPts;
        this.defencePts = defencePts;

        // DOM ELEMENT CONSTRUCTORS:    
        this.img = "style='background: #444 url(" + imgSource + ") no-repeat center'";
        this.char_card_name = "<h3>" + this.name + "</h3>";
        this.char_card_hitdef = "<h4>" + this.attackPts + "/" + this.defencePts + "</h4>";
        this.char_card = "<div class='fighter " +  faction + "' " + "id='" + this.name + "'>" + this.img + this.char_card_name + this.char_card_hitdef + "</div>";

在稍后的游戏功能中,我修改了这个“Fighter”对象的attackdefense 点,并且按预期工作,我的console.log() 测试验证连接的属性也更新。 . . .直到最后的字符串将它们拉到一起并显示:

this.char_card = "<div class='fighter " +  faction + "' " + "id='" + this.name + "'>" + this.img + this.char_card_name + this.char_card_hitdef + "</div>";

当我记录这个属性时,那些攻击和防御数字并没有改变,即使它们在之前的属性中更新成功,this.char_card_hitdef

我在这里可以忽略什么?我爬遍了整个网络,寻找范围或变量引用问题,但我的日志语句让我回到了这个关键点。

【问题讨论】:

  • faction 属性在哪里定义?
  • faction 是另一个属性,我只是将其精简以防止这篇文章变得繁琐,但我可以看到这个遗漏会造成混乱。
  • 你会接受吗?

标签: dom concatenation javascript-objects object-properties


【解决方案1】:

因为还在构造函数中,所以需要引用不带this.的变量是ObjectFighter的参数AND属性

所以改变 this.char_card = "&lt;div class='fighter " + faction + "' " + "id='" + this.name + "'&gt;" + this.img + this.char_card_name + this.char_card_hitdef + "&lt;/div&gt;";

this.char_card = "&lt;div class='fighter " + faction + "' " + "id='" + name + "'&gt;" + this.img + this.char_card_name + this.char_card_hitdef + "&lt;/div&gt;"

以及所有其他引用它们上面的属性的属性。

您可以阅读有关构造函数的更多信息here

【讨论】:

  • 谢谢马文,我现在正在尝试,并且正在打开Reference Error: img is not defined。但是,它不会在之前被 factionname 变量捕获。在&lt;div&gt; 标签内添加this.propname 不会出错,但也不会更新。它是否可能是它不喜欢的 &lt;div&gt; 内容的变量?
  • 凯文你好,很抱歉造成混乱,我忘了你只能在它是一个参数的情况下使用它。我将编辑我的帖子
  • 因此,换句话说,您在定义对象实例(并调用构造函数)时为未作为参数传入的属性添加 this.。当它不是一个参数并且定义为this.propertyname = propertyname上面时,您必须简单地使用属性变量名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2019-05-13
  • 1970-01-01
相关资源
最近更新 更多