我的递归函数正在中断,我不知道为什么。我正在尝试使用准系统 javascript 为 json 编写一个解析器到 css 并且似乎无法理解为什么我的函数不起作用。谁能帮我一把?
在 css 中,您将获得属于您正在处理的特定元素的子元素,如下所示
#nav li{
some style here
}
试图在 javascript 中操作相同的东西是行不通的。到目前为止,我的代码适用于简单的选择器。
var json = {
"body" : {
"background": "#303030",
"color": "#FFFFFF",
"font-family": "Arial, Helvetica, sans-serif"
},
"#nav": {
"li": {
"display": "inline-block",
"list-styles": "none",
"margin-right": "10px",
"padding": "10px, 10px"
}
}
}
// How to use:
// json is an obj
// body is a selector
// background is a property belong to a selector
// #303030 is a value for the property
//apply css changes to document without writing any css
//by default the first values are
// selector = background
// parent = document
// object = json
function styleApply(selector, parent, object){
var element, onSelector, signal;
//checks the first character of the selector and grabs element from page depending on what type of element it is
switch(selector[0]){
case ".":
element= parent.getElementsByClassName(selector.substring(1));
newParent = element[0]; //checks to see what is in the first index of the obtained element
break;
case "#":
element= parent.getElementById(selector.substring(1));
newParent = element;
break;
default:
element= parent.getElementsByTagName(selector);
newParent = element[0];
break;
}
//only works if there is actually an element in the page corresponding with the selector
if(newParent != null){
//loops through all elements with the same selector or in the case of id just does one loop
for(var i=0; i<element.length; i++){
//loops through all properties in the selector
for (var property in object[selector]){
//grabs the associated value with the selector could be string or object
var value= object[selector][property];
//if it is a string it is a style, if it is an object, it is targeting the elements inside the current selector only
if(typeof(value) === "string"){
element[i].style.setProperty(property, value);
}else{
/*I am breaking my code right here*/
//reusing the same function, this time selector is equal to property for the case of nav, it is the element 'li'
//newParent is the element who is a parent of the current element (e.g 'nav' is parent of 'li')
//value is the new object that is replacing json,
styleApply(property, newParent, value); //since value is an object it did not pass the string test and now the new object is value
/*Problem ends here */
}
}
}
}
}
my code for looping over all the values in json
for (var selector in json){
styleApply(selector, document, json);
}