【问题标题】:How to loop through the form which has random elements如何遍历具有随机元素的表单
【发布时间】:2017-12-27 07:06:39
【问题描述】:

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

这是我尝试过的。

在 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>

jQuery 代码:

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

【问题讨论】:

  • 您在一些地方将“label”拼错为“lable”。特别是,您可能需要 &lt;label&gt; 元素而不是 &lt;lable&gt;

标签: javascript jquery


【解决方案1】:

你需要遍历标签,而不是表单

$("#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');
                }
      });

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

稍微修剪一下

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

【讨论】:

  • @MithunRaikar 这是一个很好的解决方案。我会尝试尽可能少地循环,所以如果你也想获得input 值,循环父元素并选择它的子元素,而不是循环两次。
【解决方案2】:

您也可以使用以下方式:-

var allLables = document.querySelectorAll("#grtform lable");
for(var i = 0; i < allLables.length; i++){
  var matchLable = "Currency type";
  var lable = allLables[i].innerText; // changed here too
  if(matchLable == lable){
    allLables[i].classList.add("matchFound");
  }
}
<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多