【问题标题】:Jquery selector string from array doesn't seem to get recognized数组中的 Jquery 选择器字符串似乎无法识别
【发布时间】:2014-09-08 05:10:12
【问题描述】:

我有多个 div id="p-1"id="p-2",其中每个 div 包含一组不同的单选按钮。

单击提交按钮时,我会检查是否选择了单选按钮并进行相应操作。

我的问题: 不管选择单选按钮,我都卡在alert('Nothing is checked!'); - 我怀疑if (!$(pArray[pArrayIndexCount]+" input[name='optionsRadios']:checked").val() / 数组中的选择器是问题所在,因为硬编码 div 可以正常工作以下内容:if (!$("#p-1 input[n..... - 有什么想法吗?

JS:

var pArrayDefaultIndex = 0;
var pArray = ["p-1", "p-2", "p-3", "p-4"];

$('.submit-btn').click(function(e){
    if (!$(pArray[pArrayIndexCount]+" input[name='optionsRadios']:checked").val()) {
      //alert('Nothing is checked!');
    }
    else {
      //alert('One of the radio buttons is checked!');
      pArrayDefaultIndex++; //count up to check radio in next container
    }
});

HTML:

<div class="p-item" id="p-1">
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1">
      text
    </label>
  </div>
  <div class="radio">
    <label>
    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
      text
    </label>
  </div>
  <button class="submit-btn">Submit</button>
</div> <!-- p-1 -->

<div class="p-item" id="p-2">
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1">
      text
    </label>
  </div>
  <div class="radio">
    <label>
    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
      text
    </label>
  </div>
  <button class="submit-btn">Submit</button>
</div> <!-- p-2 -->

【问题讨论】:

    标签: jquery forms jquery-selectors radio-button


    【解决方案1】:

    您缺少 id selector(#) - p-1 是包装器元素的 id,因此您需要将它与 id 选择器一起使用。

    $('#' + pArray[pArrayIndexCount]+" input[name='optionsRadios']:checked")
    

    if条件的另一种写法是

    if (!$('#'+ pArray[pArrayIndexCount]+" input[name='optionsRadios']").is(':checked')) {
    

    【讨论】:

      【解决方案2】:

      您的选择器中缺少#

      此外,您可能希望将代码放入循环中,因为您似乎在递增 pArrayDefaultIndex,但您的代码只会被调用一次。我个人建议在他们身上放置一个类而不是一个 ID,并使用类似...

      $(".yourclass").each(function(){
          // Find your input element in relation to this object
      });
      

      这将对匹配该选择器的所有元素执行对象,即所有具有yourclass类的元素

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        • 2012-04-13
        • 2020-12-08
        • 1970-01-01
        • 2011-06-26
        相关资源
        最近更新 更多