繁体   English   中英

通过检查值是否存在来应用 css

[英]apply css by checking if value exists

我有一个里面有对象的数组。 我正在尝试做的是遍历数组并通过键检查值是否存在,如果它确实将 CSS 应用于 div 但现在即使该值存在指定的 CSS 不应用它只是应用“其他”CSS。 为什么会发生这种情况,我该如何解决? 提前致谢。

 let testArray = [{"length": "None", "duration": "10000", "percentage": "65"}, {"width": "Half", "detail": "under", "duration": "25000", "percentage": "25"}, {"length": "Full", "duration": "20000", "percentage": "90"}] testArray.forEach((obj) => { if (obj.length?.toLowerCase() == 'none') { $('.test').css('background-color', 'red') } else { $('.test').css('background-color', 'blue') } });
 .test { width: 30%; height: 40%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'> <p>testing</p> </div>

它变为红色,因为第一个值等于无,但接下来的两个值不等于无,所以它两次变回蓝色,所以当你在循环中获取对象时,你必须再次检查它们是否有任何属性有一个值 None 然后跳出两个循环。

 let testArray = [{"length": "None", "duration": "10000", "percentage": "65"}, {"width": "Half", "detail": "under", "duration": "25000", "percentage": "25"}, {"length": "Full", "duration": "20000", "percentage": "90"}] let checkIfNoneIsFound=0; testArray.every((obj) => { Object.values(obj).every((val)=>{ if(val.toLowerCase()=='none'){ $('.test').css('background-color', 'red'); checkIfNoneIsFound+=1; return false; } return true; }) if(checkIfNoneIsFound==1) { return false; } $('.test').css('background-color', 'blue') return true; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'> <p>testing</p> </div>

您的代码循环遍历obj并每次更改background-color ,最后将其更改为red

尝试这样做:

 let testArray = [ {"length": "none", "duration": "10000", "percentage": "65"}, {"width": "Half", "detail": "under", "duration": "25000", "percentage": "25"}, {"length": "Full", "duration": "20000", "percentage": "90"}] testArray.forEach((obj) => { if (obj.length?.toLowerCase() == 'none') { var para = document.createElement("p"); para.setAttribute("id", obj.index); para.setAttribute("class", "red"); para.innerText = obj.percentage; $(".test").append(para); } else if (obj.length?.toLowerCase() == 'full') { var para = document.createElement("p"); para.setAttribute("id", obj.index); para.innerText = obj.percentage; para.setAttribute("class", "gray"); $(".test").append(para); } else { var para = document.createElement("p"); para.setAttribute("id", obj.index); para.innerText = obj.percentage; para.setAttribute("class", "yellow"); $(".test").append(para); } });
 .red{ background: red } .gray{ background: gray } .yellow{ background: yellow }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'> </div>

在这种情况下,最简单的方法是使用前端框架,如 react、handlebars 等。

想法是,在这些框架上,您将根据结果呈现您的代码,例如反应:(请注意,这直接在HTML上)

 {testArray.map(()=>{ (obj.length?.toLowerCase() == 'none' ) ? <div>Some info</div> : <div>Some different info</div> })}

“你想要实现的是当值存在于数组的任何元素中时应用红色背景,否则应用蓝色背景,你能确认吗?” ——里戈贝托·拉米雷斯·克鲁兹

“@RigobertoRamirezCruz 是的” ——认真

需要发布,因为问题不清楚。 下面的例子是一个可重用的函数。 结果在 HTML 中如下所示:

<mark style="color:red">0</mark>  <!-- {"length": "None",    -->
<mark style="color:blue">0</mark> <!--  "duration": "10000", -->
<mark style="color:blue">0</mark> <!--  "percentage": "65"}, -->
<mark style="color:blue">1</mark> <!-- {"width": "Half",     -->
<mark style="color:blue">1</mark> <!--  "detail": "under",   -->
<mark style="color:blue">1</mark> <!--  "duration": "25000", -->
<mark style="color:blue">1</mark> <!--  "percentage": "25"}, -->
<mark style="color:blue">2</mark> <!-- {"length": "Full",    -->
<mark style="color:blue">2</mark> <!--  "duration": "20000", -->
<mark style="color:blue">2</mark> <!--  "percentage": "90"}; -->
<!--
This is the result if "length" and "None" were the 2nd and 3rd @param 
(the only <mark> that has red text)
-->

细节在例子中注释

 let testArray = [{"length":"None","duration":"10000", "percentage":"65"}, {"width":"Half","detail":"under","duration":"25000","percentage":"25"}, {"length":"Full","duration":"20000","percentage":"90"}]; // Reference the element that'll display results const test = document.querySelector('.test'); /** * @desc - Given an array of objects, a key and a value, generate a <mark> * with an index of the current object for each key/value pair. * If a pair matches the 2nd and 3rd @param the index will be red. * @param {array<object>} array - An array of objects * @param {string} key - The first string of a pair representing a property * name * @param {string} val - The second string of a pair representing a value * @param {object<DOM>} node - The DOM Object that the results will be * displayed in @default is <body> */ function findKV(array, key, val, node = document.body) { // Prepare key/val for comparison -- matching is case insensitive key = key.toLowerCase(); val = val.toLowerCase(); // For each object of the array... array.forEach((obj, idx) => { /* Convert object into an array of pairs -- pass the destructed [key, value] array pair */ Object.entries(obj).forEach(([k, v]) => { /* Compare with a ternary: If key equals k AND val equals v color is red -- otherwise it's blue */ let color = key === k.toLowerCase() && val === v.toLowerCase() ? 'red' : 'blue'; /* Generate a <mark> with an index of current object with the appropriate color */ node.innerHTML += `<mark style='color:${color};font-size:4rem;'> ${idx} </mark>`; }); }); // Add a line-break node.innerHTML +=`<br>`; } findKV(testArray, 'length', 'None', test); findKV(testArray, 'percentage', '25', test); findKV(testArray, 'duration', '20000', test);
 html {font: 400 1ch/1 Consolas} .test {outline: 4px dashed brown}
 <div class='test'></div>

暂无
暂无

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

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