可根据与对象对匹配的DOM值动态更改Javascript变量

时间:2018-09-19 14:36:19

标签: javascript

假设我有以下obj;

SELECT [Current Year].ID, 
[Current Year].Returning, 
[Current Year].LastName, 
[Current Year].FirstName, 
[Current Year].[Anticipated Arrival Date], 
[Current Year].Position, 
[Current Year].Email, 
[Current Year].State, 
[Current Year].[21+ yes/no], 
[Current Year].[Will turn 21 while here?], 
[Current Year].[Driver yes/no], 
[Current Year].International, 
[Current Year].[Person requesting background check be run], 
[Current Year].[Cost Center], 
[Current Year].[Account Code to charge for BG checks], 
[Current Year].[Project Code], 
[Current Year].[Emailed CBC (date)], 
[Current Year].[Received Release Form (date)], 
[Current Year].[Ran Background Check], 
[Current Year].[Emailed reminder (date)], 
[Current Year].[Emailed Staff DHS (date)], 
[Current Year].[Received DHS Forms (date)], 
[Current Year].[Mailed/Fax DHS Forms (date)], 
[Current Year].CBCcom, 
[Current Year].ICHAT, 
[Current Year].[Driving Record], 
[Current Year].[Voluntary Discl], 
[Current Year].DHS, 
[Current Year].[DHS Not Needed], 
[Current Year].Notes, 
[Current Year].[No] INTO [Year being backed up?]
    FROM [Current Year]
    ORDER BY [Current Year].LastName, [Current Year].
firstname;

然后我有一个DOM,它输出页面中所选对象的“ desc”值,例如:

var set = [
    {"desc":"Standard","code":"C1S"},
    {"desc":"Superior","code":"B2T"},
    {"desc":"Standard","code":"A1K"}
];

上述document.querySelector返回“标准”,“高级”或“豪华”。

我想在JS中创建一个变量,该变量返回所选内容的对应“代码” vvalue。例如,如果上述document.querySelector返回“ Standard”,则我需要此新变量的值=“ C1S”。

有人可以帮忙吗? 在此先感谢。 答:

2 个答案:

答案 0 :(得分:2)

一种替代方法是使用函数find

假设target = document.querySelector('.ResRoom .infoIcoAfter').innerHTML;

旁注:改用textContent以避免样式,嵌套元素等问题。

let target = 'Standard',
    set = [{"desc":"Standard","code":"C1S"},{"desc":"Superior","code":"B2T"},{"desc":"Standard","code":"A1K"}],
    found = set.find(({desc}) => desc === target),
    code = found ? found.code : '';

console.log(code);

答案 1 :(得分:0)

在您的示例中,您对Standard的匹配项不止一个,因此以下函数将返回一个数组。

import java.util.Random;
public class Program
{
public static void main(String[] args) {
Random input =new Random();
    int a = 3;
    int b = 6;
    int c =input.nextInt(b-a)+a;

    switch(a){
       case 2:
       System.out.println("*");
       break;
       case 5:
       System.out.println("*  *");
       break;
       case 6:
       System.out.println("* \n * \n  *");
       break;
      case 4:
       System.out.println("*  * \n*  *");
       break;
       case 1:
       System.out.println("*   *\n  *\n*   *");
       break;
       case 3:
       System.out.println(" *  *  *\n\n *  *  *");
       break;


           }
    }
}