【问题标题】:error jquery elements DOM错误 jquery 元素 DOM
【发布时间】:2012-08-01 18:24:59
【问题描述】:
  var foto = 'htp://midomain.com/folder/pic.jpg';
  var img = new Image();
  $(img).attr({'src': foto, 'width':'100', 'height': '100'})
        .load(function(){
          $(this).hide();                                   
          $(this).fadeIn('slow');
    })
    .click(function(){
      var ancho = 0;
      var img2 = new Image();
      $(img2)
       .attr('src', $(this).attr('src'))
       .load(function(){
            $(this).hide();                                 
            $(this).fadeIn('slow');
            ancho = $(this).width();
            $(img2).attr({'width': $(this).width(), 'height': $(this).height()});
       });

$('body').appendTo(img);

console.log(ancho); //0
console.log($(img2).attr('width')); //undefined
//get width img2 :(

alguien puede obtener el valor de 宽度和高度

有人可以帮帮我,我需要获取元素 img2 的宽度

编辑: 我需要图片的原始宽度 谢谢

【问题讨论】:

  • 切换.attr.load的顺序。在设置src属性之前绑定加载事件。
  • 我需要图片的原始宽度
  • 最后未定义的控制台日志,应该是未定义的。将它们移动到加载事件内部,否则它们会在加载事件之前发生。

标签: jquery dom element


【解决方案1】:

您有一个范围问题,并且您绑定加载事件和设置属性的顺序存在一个小问题。

var foto = 'https://www.toontrack.com/getdbimage.asp?myproducts=7';
var img = new Image();
$(img).load(function() {
    $(this).hide();
    $(this).fadeIn('slow')
}).attr({
    'src': foto,
    'width': '100',
    'height': '100'
}).click(function() {
    var ancho = 0;
    var img2 = new Image();
    $(img2).load(function() {
        ancho = this.width;
        console.log(ancho);
    }).attr('src', $(this).attr('src'));
}).hide();
$('body').append(img);​

演示:http://jsfiddle.net/9yw5H/

另外,您可以使用 html5 将其缩短为:

var foto = 'https://www.toontrack.com/getdbimage.asp?myproducts=7';
var img = new Image();
$(img).load(function() {
    $(this).hide();
    $(this).fadeIn('slow')
}).attr({
    'src': foto,
    'width': '100',
    'height': '100'
}).click(function() {
    var ancho = this.naturalWidth;
    console.log(ancho);
}).hide();
$('body').append(img);​

演示:http://jsfiddle.net/9yw5H/1/

【讨论】:

  • 加载后获取width的值
  • 图片已经加载完毕,img2包含和img1一样的img,使用html5版本不用创建img2就可以得到原来的宽度。
【解决方案2】:
  var ancho = 0;
  var img2 = new Image();
  $(img2)
   .attr('src', $(this).attr('src'))
   .load(function(){
        $(this).hide();                                 
        $(this).fadeIn('slow');
        ancho = $(this).width();
        $(img2).attr({'width': $(this).width(), 'height': $(this).height()});
   });

在此代码块之前添加:

$(那个) = $(这个)

然后像这样使用 $(that):

$(img2) .attr('src', $(that).attr('src') ...等

问题在于,当您为 $(img2) 调用链式函数时,$(this) 的范围现在指的是 img2,而不是 img1。

【讨论】:

  • 不,它没有。 $(this) 在代码中的那一点是指img1,因为点击了img1,而不是img2
  • 是的,确实如此。一旦你“进入”了 img2 对象,$(this) 就指向那个对象而不是调用对象。这是 JQuery 中常见的范围问题。
猜你喜欢
  • 2018-06-11
  • 2014-03-18
  • 2022-12-05
  • 2011-10-21
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 2010-10-12
相关资源
最近更新 更多