简体   繁体   中英

jQuery setting css background image

I am setting backgrounds dynamically using a jQuery script however the .css function does not seem to be working. Here is the script:

$(document).ready(function () {

    $(".VociMenuSportG").each(function () {

        var fullHref = $(this).find('a').attr('href');
        console.log(fullHref);
        var pos = fullHref.indexOf("IDSport=") + 8;
        console.log(pos);
        var sportNum = fullHref.substr(pos, 3);
        console.log(sportNum);
        var imageName;

        switch (sportNum.toString()) {

            case '523':
                imageName = "../Images/soccer_ball01.png";
                break;
            case '468':
                imageName = "../Images/soccer_ball01.png";
                break;
        }

        console.log(imageName);
        $(this).css('background-image', 'url (' + imageName + ')');

    });
});

The script runs through each item (VociMenuSportG), finds the path of the link in the list item and then sets the background image of the list item. The script successfully runs with no errors and using the console.logs I can see the correct path is chosen. But the background-image simply does not set ? I am wondering if I am maybe using the .css function incorrectly somehow ??

EDIT

Tried setting the paths of the images to absolute paths rather than relative ones but still no luck

您遇到的问题是url(之间的空格。请删除该空格。

 $(this).css('background-image', 'url(' + imageName + ')');

Correct form of using that method is this:

$(this).css( { 'background-image' : 'url(' + imageName + ')' } );

I would give you more info to fix it, if you had created a fiddle.

I'm not sure what's wrong, but first of all try to set another css property and see if that works.

For example: Css('border', '1px solid red')

Also I spotted a space between 'url' and '('. Maybe that doesn't work?

If it doesn't: have you tried setting the property manually from the browser-debug-toolbar to test if the URL you use is in fact the right one? The fact that you use '../' in your url makes me doubt. The ../ is often being used in css files to point from /css to /images for example. But in this case you are not in /css. So try: '/Images/soccer_ball01.png' for instance.

(Edit: while writing the answer was already posted, but well, maybe this will clarify how to debug next time... :) )

Suggestion:

You can use background instead of background-image like this way:

$(this).css('background', 'url(' + imageName + ')');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM