为什么?每个函数都工作错误

Why is this .each function working wrong

本文关键字:工作 错误 函数 为什么      更新时间:2023-09-26

我有这个功能来打印所有具有属性[proto]<img>的图像维度。

当我用这个each方法尝试函数时,它只返回一个函数。

错在哪里?

function size(){
    var $img = $('img[proto]');
    $($img).each(function(){
        var height = $(this).height;
        var width = $(this).width;
        $(this).parent().find('p').remove();
        $(this).parent().append('<p class="size">' + width + '-' + height + '</p>');
    });
}
size();

这些是函数,而不是属性、高度和宽度:

var height = $(this).height();
var width = $(this).width();
  1. 改变你的元素宣言。因为你是这样做的:$($('img[proto]'))。通过这种方式,您可以将元素两次强制转换到jQuery中
  2. widthheight是函数,而不是属性。所以你需要加括号

function size() {
    $('img[proto]').each(function() {
        var height = $(this).height(),
            width = $(this).width();
        $(this).parent().find('p').remove();
        $(this).parent().append('<p class="size">' + width + '-' + height + '</p>');
    });
}
size();

我甚至宁愿只得到你需要的元素一次。按照您的方法,将this四次强制转换为jQuery对象,并搜索两次父对象。性能可以保存。

var element = $(this),
    parent = element.parent(),
    height = element.height(),
    width = element.width();
parent.find('p').remove();
parent.append('<p class="size">' + width + '-' + height + '</p>');

如果你想直接执行函数,你可以使用IIFE,或者只需移除函数并直接执行它。

(function() {
    $('img[proto]').each(function() {
        // ...
    });
})();