You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现图片加载失败时移除image-holder元素右内边距的jQuery函数

Fix: Remove Right Padding on .image-holder When Image Fails to Load

Hey there, let's get this sorted for you! The issue with your current code is that it's targeting the <img> element's padding, but you actually need to adjust its parent container with the .image-holder class. Here's how to fix it properly:

Option 1: Direct CSS Adjustment (Quick Fix)

Update your jQuery code to target the parent .image-holder instead of the image itself. We'll use .closest() to safely find the parent container even if there's extra nesting in your HTML:

$("img").error(function(){
  // Find the nearest parent with .image-holder class and remove its right padding
  $(this).closest(".image-holder").css("padding-right", "0px");
});

Option 2: CSS Class Approach (Best Practice)

For better separation of concerns (keeping styles in CSS, behavior in JS), add a helper class to your CSS first:

.image-holder {
  height: 100px;
  width: auto;
  display: block;
  float: left;
  top: -4px;
  position: relative;
  clear: both;
  padding-right: 25px;
}

/* Add this new class to override padding when needed */
.image-holder.no-right-padding {
  padding-right: 0;
}

img {
  height: 100px;
  width: auto;
  display: block;
}

Then update your jQuery to add this class instead of directly modifying CSS:

$("img").error(function(){
  $(this).closest(".image-holder").addClass("no-right-padding");
});

This way, if you ever need to adjust the padding value later, you only have to edit the CSS instead of touching your JavaScript.

Quick Compatibility Note

If you ever upgrade to jQuery 3.0 or later, the .error() method is deprecated—you'll want to use .on("error", ...) instead:

$("img").on("error", function(){
  $(this).closest(".image-holder").addClass("no-right-padding");
});

Since you're using jQuery 2.1.1 right now, though, your original method will work just fine.

内容的提问来源于stack exchange,提问作者Matt Wallis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:18:52