这个简单的javascript在做什么?

What is this simple javascript doing

本文关键字:什么 javascript 简单      更新时间:2023-09-26

我正在阅读一个教程,一直卡在第一行代码上,我知道php中的"new"是创建一个对象,但本教程与此无关。请帮助

  var img = new Image();

教程在这里:

http://jqueryfordesigners.com/image-loading/

好了,我找到了预定义javascript对象Image()的W3定义:http://www.w3schools.com/jsref/dom_obj_image.asp

实际上,在JavaScript中,new在制作对象时也使用,就像PHP一样。

因此,您可以猜到,这行代码只是实例化了一个Image对象,并将其赋值给img变量。

这与jQuery无关。

Image是一个原生JavaScript对象,对应于HTML图像对象。

表示该行的含义"创建一个新的变量'img',并将其设置为一个新初始化的图像对象"

您可以使用

预加载图像
  var img = new Image();

他们预加载图像images/headshot.jpg

然后等待,直到加载完成

然后隐藏正在加载的图像并使图像淡出

这是一个html表单。

有关详细信息,请参阅http://www.devguru.com/technologies/ecmascript/quickref/image.html

希望这对你有帮助。

或者你想知道它创建

var img = new Image();

而不使用?

$(img)
  // once the image has loaded, execute this code
  .load(function () {
    // set the image hidden by default    
    $(this).hide();
    // with the holding div #loader, apply:
    $('#loader')
    // remove the loading class (so no background spinner), 
    .removeClass('loading')
    // then insert our image
    .append(this);
    // fade our image in to create a nice effect
    $(this).fadeIn();
  })
    // if there was an error loading the image, react accordingly
   .error(function () {
   // notify the user that the image could not be loaded
   })
// *finally*, set the src attribute of the new image to our image
.attr('src', 'images/headshot.jpg');
});

'this'关键字代表img变量