如何动态将图片URL设置为提交按钮的background-image
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
forloop, grab the image URL at indexjfrom theproparray. - Properly format the
background-imageCSS value: CSS requires image URLs to be wrapped inurl(), 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
vardeclarations fordivElem,elem, andbankIdto 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 forcontainif you want the full image visible even if it doesn’t fill the button. - Tweak the
widthandheightvalues to match the actual dimensions of your images for the best display.
内容的提问来源于stack exchange,提问作者abhishek vashistha
相关产品推荐
相关产品推荐

