【问题标题】:I'm having an issue making/updating HTML elements.- Javascript我在制作/更新 HTML 元素时遇到问题。- Javascript
【发布时间】:2014-06-30 17:20:48
【问题描述】:

我一遍又一遍地查看这段代码,但似乎找不到问题所在。我想要做的是在屏幕上出现一个滑动条,比如健康/法力条。 这是我用来创建栏的函数:

function makeBar(max,color,place){
    b=new Object();
    len=bar.length;
    bar.push(b);
    b.index=len;
    b.place=place;
    b.color=color;
    b.max=max;
    b.val=max;
    b.print=function(){
        this.place.innerHTML+="<div id='bar"+this.index+"' style='display:inline-block;text-align:center;height:40px;width:200px;border:3px outset black;'><div id='subBar"+this.index+"' style='font-size:20pt;height:34px;width:1px;background:"+this.color+";border:3px outset "+this.color+";'></div></div>";
        this.container=document.getElementById('bar'+this.index);
        this.content=document.getElementById('subBar'+this.index);
    }
    b.refresh=function(){
        this.content.style.width=(this.val/this.max)*194+"px";
    }
    b.print();
}

所以它可以完美地制作和“打印”条形图。 但是当我尝试使用

bar[0].refresh();

它什么也不做,除非 bar[0] 是唯一的 bar。 基本上,只有最后创建的 bar 才能成功使用它自己的 refresh() 方法。 谁能帮我? 谢谢大家1

【问题讨论】:

  • 你能创建一个小提琴来演示这个问题吗? jsfiddle.net

标签: javascript html object refresh


【解决方案1】:

对象B有刷新功能吗?您可以尝试将“b”作为全局变量而不是在本地使用它。

 var b;
function makeBar(max,color,place){
 b=new Object();
 len=bar.length;
 //bar.push(b);  don't push here
 b.index=len;
 b.place=place;
 b.color=color;
 b.max=max;
 b.val=max;
 b.print=function(){
    this.place.innerHTML+="<div id='bar"+this.index+"' style='display:inline-block;text-align:center;height:40px;width:200px;border:3px outset black;'><div id='subBar"+this.index+"' style='font-size:20pt;height:34px;width:1px;background:"+this.color+";border:3px outset "+this.color+";'></div></div>";
    this.container=document.getElementById('bar'+this.index);
    this.content=document.getElementById('subBar'+this.index);
}
b.refresh=function(){
    this.content.style.width=(this.val/this.max)*194+"px";
}
b.print();
}

如果你想使用对象 b 的单个实例,那么不要使用数组。直接拨打b.refresh()

【讨论】:

  • 当我在创建 2 个 bar 实例并分别在控制台中输入 bar[0] 和 bar[1] 后使用 Chrome 的“检查元素”时,bar[0] 具有 div#bar0 和 div# subBar0 分别是容器和内容属性,它们是页面上的真实元素,但是当我将鼠标悬停在它上面时,它不会像使用 bar[1] 那样突出显示元素。如果我创建很多条形图也是如此。只有创建的最后一个 bar 对象会执行此操作。我不知道为什么......
猜你喜欢
  • 2017-10-12
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 2022-07-11
  • 2014-06-13
相关资源
最近更新 更多