基于JS Object变量添加body类

时间:2017-10-12 08:59:38

标签: javascript jquery

我有一个JS对象,如下所示,带有几个viariables - 我用它来将一些数据推送到我的网站上的元素 - 我想知道是否有可能在主体中添加一个类,其名称与company变量?那么,如果该变量中的数据会说“苹果电脑”,那么可以将“applecomputers”或“apple”和“computer”添加为一个体型吗?

var retailerData = {
    "del": {
        "zip": "",
        "city": ""
    },
    "user": {
        "country": "",
        "phone": "0",
        "nbrOrders": ,
        "isPunchOut": false,
        "name": "",
        "company": "name name name",
        "salesPerson": "",
        "customerNo": "",
        "email": "d"
    },
    "order": {
        "shippingSum": 0.0,
        "shippingFormatSum": "0:-",
        "orderno": "0",
        "orderFormatSum": "595:-",
        "formatQty": "1 ",
        "voucher": "",
        "orderFormatVat": "148,75:-",
        "currencySymbol": ":-",
        "currency": "SEK",
        "orderVat": 148.75,
        "orderSum": 595.0,
        "items": [{
            "imageURI": "\/imgr\/84c2bfee-ff5b-462c-89d3-dc73b338c890\/70\/70",
            "qtyAvail": 0,
            "price": 595.0,
            "qty": 1,
            "artno": "U4414E",
            "vat": 148.75,
            "formatVat": "148,75:-",
            "id": "20730",
            "label": "",
            "category": "",
            "formatPrice": "595:-",
            "manufacturer": "HP"
        }]
    }
}

3 个答案:

答案 0 :(得分:0)

就像

一样简单
var company = retailerData.user.company;
company.split( " " ).forEach( function( item ){
    $( "body" ).addClass( item );
});

答案 1 :(得分:0)

如果你想使用普通的旧版香草JavaScript。以下应该有效。

document.body.className += " " + retailerData.user.company;

需要空间以确保它是一个新类而不是更改现有类。

或者,下面更现代的方法(IE10以下不支持)更灵活。

document.body.classList.add(retailerData.user.company);

您还可以将其与一些字符串操作相结合,以更改"苹果电脑"进入" applecomputers"如你所说。

retailerData.user.company.replace(/\s/g, '');

答案 2 :(得分:0)

  1. 班级名称将是' namenamename'

    var companyClass = retailerData.user.company.replace(" ", "");
    
    $("body" ).addClass( companyClass );
    
  2. 班级名称将是' name-name-name'

    var companyClass = retailerData.user.company.replace(" ", "-");
    
    $("body" ).addClass( companyClass );