javascript - 使用对象方法设置 html 值真的很奇怪

标签 javascript html

我最近才开始学习 JS,尽管我对其他语言的编码并不陌生,但 JS 经常让我感到困惑。

如果我创建多个对象,构造函数的“CarFail”版本(不使用 JQuery)将不起作用(仅创建一个对象时效果很好)。构造函数的第二个“汽车”版本(使用 JQuery)效果很好。

我不明白为什么第一个构造函数版本失败。

我显然遗漏了一些微不足道的东西。

<div id="main"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

    function CarFail(x,y)
    {
        this.x=x;
        this.y=y;

        document.getElementById("main").innerHTML += '<img src="http://nostarch.com/images/car.png"/>';

        this.gelement=document.getElementById("main").lastChild;

        this.draw=function()
        {
            this.gelement.style.position="absolute";
            this.gelement.style.top=this.y+"px";
            this.gelement.style.left=this.x+"px";
        };
        this.draw();
    }

    function Car(x,y)
    {
        this.x=x;
        this.y=y;

        var carhtml = '<img src="http://nostarch.com/images/car.png"/>';

        this.gelement = $(carhtml);

        this.draw=function()
        {
            this.gelement.css({
                position: "absolute",
                left: this.x,
                top:this.y
            });
        };

        $("#main").append(this.gelement);
        this.draw();
    }

    var car1 = new Car(10,20);
    var car2 = new Car(50,90);

    car1.x=150;
    car1.draw();

</script>

最佳答案

重写 innerHTML 会更改该元素下的整个文档层次结构,因此之前存储的任何引用都会丢失。

我建议您改为使用 DOM 方法

let img = document.createElement('img')
img.src = 'http://nostarch.com/images/car.png'
this.gelement = document.getElementById("main").appendChild(img)

关于javascript - 使用对象方法设置 html 值真的很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432678/

相关文章:

javascript - 如何在javascript中获取城市或国家的时区

html - 只有第一个媒体查询在 851px 以上有效,但其他媒体查询无效

javascript - .click 函数不适用于使用 .fadeIn 加载到 div 中的内容

html - 在模态窗口中居中 div

javascript - 如何为 Vue 中 v-for 创建的每个按钮组设置 accesskey?

javascript - 内联 JavaScript 与 CSP 级别 1 结合使用

javascript - 计算每个表中的多个数字

javascript - 我在异步函数中使用 Promise 是否正确?

javascript - P5.js 中的随机球速

html - 在 Delphi 中使用 TIdHTTP 提交表单并检索数据(不是通常的)