jQuery background-image JSON问题,url("")追加为空

时间:2017-07-17 19:02:48

标签: jquery html json

所以我有以下代码,除了.css('background-image')更改外,它们都完美无缺。您会看到url("");为空。不知道为什么,我希望也许有人可以快速看看,让我知道可能出现的问题?我只提供了代码,因为除了这一件之外的所有其他工作。

HTML(jQuery附加后):

<td class="RarityBG" style="background-image: url("");">
   <img src="img/trinket/trinket01.png">
</td>

jQuery(注意.html追加工作100%):

    var trinketJSON
    $.getJSON('js/trinket.json', function (data) {
        trinketJSON = data;
        console.log(trinketJSON);

        $.each(trinketJSON, function(i, item) {
            $('<tr>').html(
                "<td class='RarityBG'><img src='" + trinketJSON[i].TrinketIMG + "' /></td><td>" + trinketJSON[i].TrinketName + "</td><td>" + trinketJSON[i].Rarity + "</td><td>" + 
                trinketJSON[i].EffectOne + "</td><td>" + trinketJSON[i].EffectTwo + "</td><td>" + trinketJSON[i].EffectThree + "</td><td>"  
                + trinketJSON[i].SetBonus + "</td>").appendTo('#trinketsTable');
            $('.RarityBG').css('background-image', 'url(' + trinketJSON[i].RarityBG + ')');
            });
        });

JSON:

  {
    "TrinketIMG": "img/trinket/trinket01.png",
    "TrinketName": "Trinket 01",
    "Rarity": "Common",
    "RarityBG": "img/trinket/rarity_common.png",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
    "SetBonus": ""
  }

2 个答案:

答案 0 :(得分:1)

如果不需要每次都循环播放,你也可以摆脱each

<script>
    var trinketJSON
    $.getJSON('js/trinket.json', function (data) {
        trinketJSON = data;
        console.log(trinketJSON);
        // just removed this for now
        $('.RarityBG').css('background-image', 'url(' + trinketJSON.RarityBG + ')');
            //console.log("RarityBG" + trinketJSON.RarityBG);
        });
    </script>

上面的脚本将能够访问所有json键,并且还将填充url。试试吧。

答案 1 :(得分:0)

不工作:

        $.each(trinketJSON, function(i, item) {
            $('<tr>').html(
                "<td class='RarityBG'><img src='" + trinketJSON[i].TrinketIMG + "' /></td><td>" + trinketJSON[i].TrinketName + "</td><td>" + trinketJSON[i].Rarity + "</td><td>" + 
                trinketJSON[i].EffectOne + "</td><td>" + trinketJSON[i].EffectTwo + "</td><td>" + trinketJSON[i].EffectThree + "</td><td>"  
                + trinketJSON[i].SetBonus + "</td>").appendTo('#trinketsTable');
            $('.RarityBG').css('background-image', 'url(' + trinketJSON[i].RarityBG + ')');
            });
        });

工作:

        $.each(trinketJSON, function(i, item) {
            $('<tr>').html(
                '<td style=\'background-image: url("' + trinketJSON[i].RarityBG + '");\'><img src="' + trinketJSON[i].TrinketIMG  + '" /></td><td>' + trinketJSON[i].TrinketName + "</td><td>" + trinketJSON[i].Rarity + "</td><td>" + 
                trinketJSON[i].EffectOne + "</td><td>" + trinketJSON[i].EffectTwo + "</td><td>" + trinketJSON[i].EffectThree + "</td><td>"  
                + trinketJSON[i].SetBonus + "</td>").appendTo('#trinketsTable');
        });