为什么?每个函数都工作错误
Why is this .each function working wrong
我有这个功能来打印所有具有属性[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();
- 改变你的元素宣言。因为你是这样做的:
$($('img[proto]'))
。通过这种方式,您可以将元素两次强制转换到jQuery中 width
和height
是函数,而不是属性。所以你需要加括号
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() {
// ...
});
})();
相关文章:
- dhtmlx多个调度器不工作错误”;调度程序未定义”;
- Javascript 确认框工作错误
- 变量中的类工作错误
- 为什么这个jQuery验证工作错误
- Cordova罗盘API(navigator.compass.watchHeading)不工作(错误代码3)
- Javascript不能在Chrome或IE9中工作-错误”;复选框未定义“;显示在FF JS控制台中
- JQuery UI对话框不能正常工作;错误信息“TypeError: undefined不是一个函数”
- Jquery/JS css动画在悬停时工作错误
- AngularJs Ng-Keypress事件工作错误
- Jquery 选择器不工作:错误:语法错误,无法识别的表达式:a[@href]
- 日期选择器范围工作错误
- 为什么我的Jquery Ajax请求不工作错误:未定义的索引:ProID
- 反应不工作.错误提示(index):13 Uncaught SyntaxError: Unexpected token
- 身份工具箱不工作-错误代码:IDP的错误响应
- jquery日期picker beforeShowDay工作错误的月份
- Javascript验证在c#中不工作(错误消息)
- 为什么?每个函数都工作错误
- 路由到api工作错误
- 子元素位置相对工作错误
- 从timeline2.6.1的例子不工作-错误链接是未定义的时间线代码0