2017-10-15 70 views
1

我寫這個代碼,它不工作jQuery的使用變量

$('.item').each(function(){ 
    var ItemGradient1 = $(this).attr('data-gradient-1'); 
    var ItemGradient2 = $(this).attr('data-gradient-2'); 
    var ItemGradient = 'linear-gradient(to right bottom, ' + ItemGradient1 + ', ' + ItemGradient2 + ');' 
    $(this).children('.portfolio-wrapper').append('<div class="item-after"></div>'); 
    $(this).children('.portfolio-wrapper').children('.item-after').css('background', ItemGradient); 
    console.log(ItemGradient); 
}); 

我認爲這doenst因爲該行的工作:

$(this).children('.portfolio-wrapper').children('.item-after').css('background', ItemGradient); 

這是HTML:

 <div class="item Others" data-cat="Others" data-path="/portfolio/others/jonasplatin_website/" data-gradient-1="#ffef80" data-gradient-2="#464646"> 
      <div class="portfolio-wrapper"> 
       <img src="/portfolio/others/jonasplatin_website/thumbnail.jpg" alt="Jonas Platin unofficial website" /> 
       <div class="desc"> 
        <h2 class="item-info">Jonas Platin unofficial website</h2> 
        <h3 class="item-info">Webdesign</h3> 
       </div> 
      </div> 
     </div> 

您是否看到錯誤?感謝您的幫助

+0

我認爲這將是一個好主意,也顯示HTML結構 –

+0

這是什麼應該做的?你突出顯示的那條線讓你認爲這是問題所在? –

回答

1

問題是這一行:

var ItemGradient = 'linear-gradient(to right bottom, ' + ItemGradient1 + ', ' + ItemGradient2 + ');' 

的CSS功能被拒絕,因爲在字符串的結尾額外; ItemGradient。刪除它,它會工作:)

既然你正在學習,這是另一種方式編寫函數:

$('.item').each(function(){ 
    var itemGradient1 = $(this).data('gradient-1'); 
    var itemGradient2 = $(this).data('gradient-2'); 
    var itemGradient = 'linear-gradient(to right bottom, ' + itemGradient1 + ', ' + itemGradient2 + ')'; 
    $(this) 
     .find('.portfolio-wrapper') 
     .append('<div class="item-after"></div>') 
     .css('background', itemGradient); 
}); 
+0

工作完美,謝謝:) – morizvonlanga