尝试使用此关键字将函数变量附加到文档

时间:2018-09-24 23:53:36

标签: javascript html

我正在尝试将图像添加到创建的对象ive内部的div中。 所以我有我的对象,我试图将元素添加到文档中。 问题是:document.this.Element.append()无法正常工作!

您将如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,那么以这种方式document访问document.this.Element.append()字段可能会给您带来麻烦。

document字段是在浏览器上下文中全局定义的,没有this字段。这将意味着document.this.Element.append()可能引发异常,这就是代码无法正常工作的原因。

假设Element字段与您的<div>相对应,请考虑执行以下操作:

var Element = document.querySelector('div'); // Get reference to div element

然后,要将图像元素添加到div中,您将像这样使用appendChild()方法:

var image = document.createElement('img'); // Create a new image element
Element.appendChild(image); // Append new image element to div

我不确定围绕DOM交互如何设置您的类,但是以下代码段可能会为您提供一些帮助的线索/指针:

// Suppose this is your class
class YourObject {
	
  constructor() {
  	
    // You might initialize an Element field in the constructor. We'll
    // set this as the div element in the DOM
    this.Element = document.querySelector('div')
  }
  
  youObjectFirstMethod() {
  	
    // In your class method, you first create a new image element like so
    var image = document.createElement('img');
    
    // Then assign your image URL to it
    image.src = 'https://pbs.twimg.com/profile_images/643157180594585601/dsaEOMIS.jpg';

	// Then attach the image element to the DOM. You can access the Element
    // field that we initalized in the constructor to attach the image to 
    // do this
    this.Element.appendChild(image)
  }
  
  youObjectSecondMethod() {
  	
    // In your class method, you first create a new image element like so
    var image = document.createElement('img');
    
    // Then assign your image URL to it
    image.src = 'https://1.bp.blogspot.com/-wqo9oAoKa8Y/UJxVWogEp5I/AAAAAAAABfg/OeN6lWUcJ3g/s1600/Egyptian-Mau-Cat_Picture.jpg';

    // You can achieve the same thing without the need for a Element field 
    // by accessing the current DOM document directly
    document.querySelector('div').appendChild(image)
  }

}

new YourObject().youObjectFirstMethod()

new YourObject().youObjectSecondMethod()
<!-- 
div is the element that your image will be appended to 
-->
<div>
</div>