简体   繁体   English

从字符串数组应用多个 CSS 规则?

[英]Applying multiple CSS rules from a String array?

I currently have the following set up for my jQuery request, which is meant to find an element on the page with the id "myid" and apply new CSS rules to it.我目前为我的 jQuery 请求设置了以下内容,这意味着在页面上找到一个 id 为“myid”的元素并对其应用新的 CSS 规则。 These rules are not known beforehand, and so I first read a file and store the results in a string array, with the even indexes being the rules and the odd indexes being the values.这些规则事先并不知道,所以我首先读取一个文件并将结果存储在一个字符串数组中,偶数索引是规则,奇数索引是值。 However, jQuery refuses to let this work.然而,jQuery 拒绝让这个工作。 I've trawled over the documentation to no avail, and all I get is that apparently words[0] is of type string[], not string (which shouldn't be the case).我已经浏览了文档无济于事,我得到的只是显然 words[0] 是 string[] 类型,而不是 string(不应该是这种情况)。

Can I get some advice on this?我可以就此获得一些建议吗? Here is an example of what I mean:这是我的意思的一个例子:

var words = ["color", "blue", "font-size", "100"]; // these have been parsed from a file and formatted

$("#myid").css({words[0] : words [1], words[2], words[3]}); // This won't apply

I think this code will help you.我认为这段代码会对你有所帮助。 I tested it on this page only.我只在这个页面上测试过。 :) :)


var words = ["color", "blue", "font-size", "100"];

for (var i = 0; i < words.length; i += 2){
  $("#mainbar").css(words[i], words[i+1]);
}

This loop will help you add any number of rules since you're reading them dynamically.这个循环将帮助您添加任意数量的规则,因为您正在动态阅读它们。

One way to do this is to build the css object first and pass it in to the jQuery function:一种方法是首先构建 css 对象并将其传递给 jQuery 函数:

 let words = ["color", "blue", "font-size", "100"]; // these have been parsed from a file and formatted const cssObj = {}; words.forEach((el,idx,arr) => { if(!(idx % 2) && (idx + 2 <= arr.length) ){ cssObj[el] = arr[idx + 1] } }); $("#myid").css(cssObj); // This won't apply
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="myid">MyId Div</div>

Here is a way to combine the CSS into one object to apply it all at once:这是一种将 CSS 组合到一个对象中以一次性应用的方法:

const words = ["color", "blue", "font-size", "100px"];


let cssObj = {};

for (var i = 0; i < words.length; i++){
    cssObj = { ...cssObj, [words[i]]: words[i+1] }
}

$("#mainbar").css(cssObj);

JSFIDDLE JSFIDDLE

While you've already accepted an answer, I thought I'd offer an alternative, with explanations in order that you – and future visitors – might learn how the solution works:虽然你已经接受一个答案,我想我会提供一个选择,以解释为了你-和未来游客-可能会学到如何解决工作:

// your original, parsed Array:
let words = ["color", "blue", "font-size", "100px"],

// we convert your array of words into a two-dimensional Array
// word-pairs, using Array.prototype.reduce():
// (Please note this approach was taken from user
// Vbyec's answer: https://stackoverflow.com/a/44996257/82548)
  pairs = words.reduce(function(result, value, index, array) {

    // if the index modulo 2 (the remainder of the index divided by 2)
    // is equal to 0:
    if (index % 2 === 0)

      // we push the sliced Array elements - taken from the copy
      // of the Array - into the result Array (the empty Array
      // passed as an argument):
      result.push(
        // here we define the start of the slice as the index
        // of the current Array-element and the end of the
        // slice before the element found at the index of
        // index of the current Array-element + 2:
        array.slice(index, index + 2)
      );
    // we then return the result:
    return result;
  }, []),
// we use Object.fromEntries() to create a new Object from
// the two-dimensional Array we created:
  cssObj = Object.fromEntries(pairs);

// we pass the created-Object to jQuery's css() method:
$('#myid').css(cssObj);

 let words = ["color", "blue", "font-size", "100px"], // these have been parsed from a file and formatted pairs = words.reduce(function(result, value, index, array) { if (index % 2 === 0) { result.push(array.slice(index, index + 2)); } return result; }, []), cssObj = Object.fromEntries(pairs); $('#myid').css(cssObj);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="myid">Some arbitrary text</div>

JS Fiddle demo . JS小提琴演示

References:参考:

Bibliography:参考书目:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM