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

如何动态将图片URL设置为提交按钮的background-image

How to Assign Image URLs from an Array as Backgrounds for Submit Buttons

Looking at your code, the main issue is that you’re not referencing the image URLs stored in your prop array—instead, you’re using an undefined imagefile variable. Here’s how to fix this and get your submit buttons showing the correct background images:

Step-by-Step Fix:

  • Access the current array element in your loop: Inside the for loop, grab the image URL at index j from the prop array.
  • Properly format the background-image CSS value: CSS requires image URLs to be wrapped in url(), so make sure to include that syntax when setting the style.
  • Add basic styling for visibility: Submit buttons have default borders and sizes that might hide your background image. Set a width/height and remove the default border to ensure the image displays properly.

Corrected Code:

var prop = [
    '${pageContext.request.contextPath}/images/acquirer_aktia.png',
    '${pageContext.request.contextPath}/images/acquirer_aktia.png',
    '${pageContext.request.contextPath}/images/acquirer_aktia.png',
    '${pageContext.request.contextPath}/images/acquirer_aktia.png'
]; 

for (var j = 0; j < prop.length; j++) { 
    var divElem = $("<div class='row'>"); 
    $('#bankList').append(divElem); 
    var elem = $("<div class='col-sm-3'>"); 
    var bankId = $("<input type='submit' >"); 
    
    // Grab the current image URL from the prop array
    var currentImgUrl = prop[j];
    // Set the background-image with proper CSS syntax
    bankId.css('background-image', 'url(' + currentImgUrl + ')');
    // Add styling to make the background image visible
    bankId.css({
        width: '120px',  // Adjust to match your image's width
        height: '60px',   // Adjust to match your image's height
        border: 'none',
        cursor: 'pointer',
        backgroundSize: 'cover' // Optional: scales image to fill the button
    });
    
    elem.prepend(bankId); 
    divElem.prepend(elem); 
}

Quick Notes:

  • I added var declarations for divElem, elem, and bankId to avoid accidental global variables (a good practice for scoping).
  • The backgroundSize: 'cover' property ensures your image scales to fit the button without distortion—swap it for contain if you want the full image visible even if it doesn’t fill the button.
  • Tweak the width and height values to match the actual dimensions of your images for the best display.

内容的提问来源于stack exchange,提问作者abhishek vashistha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:48:41