2015-04-05 90 views
0

我寫了一個函數,考慮div的高度和寬度,現在我找不到我寫代碼的地方,用逗號輸出值 舉例:#div_0 {height:13.3%; 寬度:28.5%; }逗號輸出

(function ($) { 
    $.fn.percent = function (el, arg2) { 
     var pol = $(this).parent() 

     if (typeof (el) != 'object') { 
      if (typeof (el) == 'number' && arg2 == 'w' || typeof (el) == 'number' && arg2 == 'width') return el * 100/parseInt(pol.css('width'))+ '%;' ; 
      else if (typeof (el) == 'number' && arg2 == 'h' || typeof (el) == 'number' && arg2 == 'height') return el * 100/parseInt(pol.css('height'))+ '%;'; 
      else return false; 
     } 
     var set = []; 
     for (var i in el) { 
      var element = parseInt($(this).css(i)); 
      if (el[i] == 'w' || el[i] == 'width') set[set.length] = '\n' + i + ': ' + element * 100/parseInt(pol.css('width'))+ '%;' ; 
      else if (el[i] == 'h' || el[i] == 'height') set[set.length] = '\n' + i + ': ' + element * 100/parseInt(pol.css('height'))+ '%;'; 
     } 
     return set; 
    } 
})(jQuery); 

var return_ = ''; 
var sharp = '#'; 

function chet_div() { 
    for (var i = 0; i < $('#container div').length; i++) { 
     if ($('#container div').eq(i).attr('id').search(/div/i) != -1) { 
      return_ += sharp + $('#container div').eq(i).attr('id') + '{\n ' + $('#container div').eq(i).percent({ height: 'h', width: 'w' }) + '\n}\n'; 
     } 
     document.getElementById('hidden_sizes').value = return_; 
    } 
    return return_; 
} 

感謝

+2

您是否要求我們調試您編寫的代碼? – vlaz 2015-04-05 21:10:03

+0

@Vld是的(我和我的朋友 – ZKolya 2015-04-05 21:23:52

回答

0

你的函數返回percent()左右,但在字符串中使用數組所以它使用toString()方法,昏迷加入值

.percent({ height: 'h', width: 'w' }) 

我建議如下用它來代替

.percent({ height: 'h', width: 'w' }).join("") 
0

你的插件構造的CSS規則數組並返回該數組:

var set = []; 
// ... 
return set; 

後來您連接該陣列的一些字符串:

'{\n ' + $('#container div').eq(i).percent({ 
    height: 'h', 
    width: 'w' 
}) + '\n}\n'; 

在這個case數組將被轉換爲String類型以及toString me的ThOD。現在,toString爲陣列,內部爲join(),它使用,作爲默認分隔符。這是你看到','的原因。

爲了解決這個問題不依靠隱式類型鑄造這種情況發生在這種情況下,但自己與正確的分隔符創建一個字符串:

'{\n ' + $('#container div').eq(i).percent({ 
    height: 'h', 
    width: 'w' 
}).join('') + '\n}\n'; 
+0

謝謝,這是個好主意 – ZKolya 2015-04-05 21:42:01