如何遍历具有随机元素的表单

Cha*_*kar 4 javascript jquery

我试图遍历在随机元素中有标签的表单,并检查标签是否与给定的标签名称匹配,如果匹配,我正在为该元素添加一个类.但是我无法让它工作,我该怎么做?

这是我尝试过的.

在div之类的随机元素中包含标签的表单

<form id="grtform">
    <div id="section-1">
        <lable>Currency type</lable>
        <input type="text" name="currencyType">
    </div>

    <div id="section-2">
        <lable>Currency rate</lable>
        <input type="text" name="currencyRate">
    </div>

        <lable>Currency of country</lable>
        <input type="text" name="currencyCountry">

    <div id="section-3">
        <div class="formData">
            <lable>Currency due</lable>
            <input type="text" name="currencyDue">
        </div>
    </div>
  </form>
Run Code Online (Sandbox Code Playgroud)

Jquery代码:

$("#grtform").each(function(){
                var matchLable = "Currency due"
                var lable = $(this).find('label').text();
                if(matchLable == lable){
                    $(this).addClass('matchFound');
                }
      });
Run Code Online (Sandbox Code Playgroud)

Sur*_*tta 5

你需要循环通过标签,而不是形式

$("#grtform lable").each(function(){ // selecting all labels of form
                var matchLable = "Currency type"
                var lable = $(this).text(); // changed here too
                if(matchLable == lable){
                    $(this).addClass('matchFound');
                }
      });
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,这指的是当前迭代标签.

修剪了一下

$("#grtform lable").each(function(){ // selecting all labels of form
                if($(this).text() == "Currency type"){
                    $(this).addClass('matchFound');
                }
      });
Run Code Online (Sandbox Code Playgroud)

  • @MithunRaikar这是一个很好的解决方案.我会尝试尽可能少地循环,所以如果你想获得`input`值,循环父元素并选择它的子元素而不是循环两次. (3认同)