【发布时间】:2020-06-19 01:26:45
【问题描述】:
所以我在搞乱 JS 试图创建一种方法,在不删除当前应用的样式的情况下向元素添加 CSS 样式:
// ==================================================================================================
// this method adds style to an element using CSS inline syntax without removing unaltered CSS styles
// ==================================================================================================
Element.prototype.cssStyle = function (style)
{
let styleChars = style.split(''); // split each character of the style arg as an item in an array
let positions = [];
for(let i=0; i<styleChars.length; i++){
if(styleChars[i] === '-'){
positions.push(i+1);
};
};
positions.forEach(function (position){ // for each match
styleChars.splice(position, 1, style[position].toUpperCase()); // make that character uppercase
});
styleChars.splice(0, 0, '[["'); // add a "[[" item on the first position
styleChars.splice(styleChars.length, 0, '"]]'); //add a "[[" on the last position
style = styleChars.join('') // join back the array into a string
style = style.replace(/:/g, "\",\"").replace(/;/g, "\"],[\"").replace(/-/g, ""); // replace some character in order to make the string look like an array
style = JSON.parse(style); // parse the string into an array
for(let i=0; i<style.length; i++){ // for each item in the array
let property = style[i][0].replace(/ */, ""); // remove some characters which might inhibit normal execution
let value = style[i][1].replace(/;/, "").replace(/ */, ""); //remove some characters which might inhibit normal execution
this.style[property] = value // change style of the element
};
return this.getAttribute('style'); //return all inline CSS styles
}
所以如果我尝试像这样设置元素的样式:
Element.cssStyle('background-color: white; color: #000')
它按预期工作,但如果我在参数字符串的末尾添加;,我会得到这个
Element.cssStyle('background-color: white; color: #000;')
'Uncaught TypeError: Cannot read property 'toUpperCase' of undefined'
即使我没有发现 replace 方法有任何明显问题,但可能是什么?
在该行替换空格可以正常工作,但尝试替换 ; 我得到了那个错误。
我的代码写得有多糟糕?
谢谢!
【问题讨论】:
-
哇...我认为您的“与 JS 混在一起”介绍在这里非常准确 :) 您想多了,过于复杂了。您永远不应该尝试自己构建 JSON 字符串。永远不会有任何借口。您无缘无故地给自己(以及您未来的自己,作为需要在 5 年内维护此代码的人)带来困难
-
感谢您的评论。以我对 JavaScript 的有限了解,这就是我所能想到的 :(。对此的任何建议或替代解决方案将不胜感激。
-
当然,我正试图弄清楚这是做什么的(因为这确实使事情更难阅读)。我只是想让你明白这一点并在未来记住它。我过去是通过艰难的方式学会它的,作为初学者,我很想早点得到这个建议。我可能会在几分钟内发布答案
标签: javascript regex methods replace prototype