交叉引用JQuery中单个匹配的两个列表

时间:2018-06-07 08:52:46

标签: jquery class

我在Javascript中有两个列表:

  • newClass - 这是一个字符串列表(类名)
  • hiddenVals - 这是$('input:hidden')隐藏的输入元素列表,其中包含值...

我基本上希望能够浏览newClass列表并检查hiddenVals中是否存在匹配项。如果是这样,我将获得该hiddenVal的值。

我有以下工作,但我可以帮助,但我认为JQuery有一个更简洁的方法:

            var newClass = ui.item[0].parentElement.classList;
            var hiddenVals = $j('input:hidden');
            var newStatusId = -1;

            for (var i = 0; i < hiddenVals.length; i++) {

                var hiddenClass = hiddenVals[i].classList[0];

                for (var x = 0; x < newClass.length; x++) {

                    var test = newClass[x];

                    if (test == hiddenClass) {
                        newStatusId = hiddenVals[i].value;
                    }
                }
            }

我希望这是有道理的,有人可以帮助对其进行适当的重构。

1 个答案:

答案 0 :(得分:0)

以下是一些建议的改进。

// use const for constant variables
const classes = ui.item[0].parentElement.classList;
// and let for variables that may change
let newStatusId = -1;

// jQuery's .each() will loop through all elements selected
$('input:hidden').each(element => {
    // for of loop is nicer syntax
    for(let c of classes) {
        // you should use === instead of == to conserve type when comparing
        // but jQuery has .hasClass() which may help
        if($(element).hasClass(c)) {
            newStatusId = $(element).value;
        }
    }
});

<强>参考
const https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
let https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
for of循环https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
.each() https://api.jquery.com/each/
.hasClass() https://api.jquery.com/hasclass/
=== Which equals operator (== vs ===) should be used in JavaScript comparisons?