输出中的逗号

Comma in the output

本文关键字:输出      更新时间:2023-09-26

我写了一个函数,它考虑了div的高度和宽度,现在我找不到我写代码的地方,用逗号输出的值示例:#div_0{高度: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_;
}

感谢

函数percent()返回一个数组so,但在字符串中使用,因此它使用toString()方法,该方法将值与coma 连接

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

我建议使用下面的

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

您的插件构建了一个CSS规则数组,并返回以下数组:

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

稍后,您将这个数组与一些字符串连接起来:

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

在这种情况下,数组也将通过其toString方法转换为String类型。现在,Array的toString在内部调用join(),后者使用,作为默认分隔符。这就是你看到","的原因。

为了克服这个问题,不要依赖于这种情况下发生的隐式类型转换,而是使用正确的分隔符自己创建一个字符串:

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