【问题标题】:Check if radio button exists jQuery检查单选按钮是否存在jQuery
【发布时间】:2015-09-11 20:23:28
【问题描述】:

我正在根据某个值将单选按钮的选中状态设置为 true;

 var radioValue = data.Activity.Answer == "Please add your answer" ? "valueA" : data.Activity.Answer;
$("input[name=optionRadio" + currentIndex + "][value=" + radioValue + "]").attr('checked', true);

对我来说,事先检查幻灯片上是否确实存在该单选按钮的最佳方法是什么?

【问题讨论】:

    标签: javascript jquery radio-button


    【解决方案1】:

    您可以查看jQuery对象的length来查找:

    if($("input[name=optionRadio" + currentIndex + "]").length > 0 ){
         // Radio button actually exists...
    }
    

    【讨论】:

      【解决方案2】:

      使用length

      if($("input[name=optionRadio" + currentIndex + "][value=" + radioValue + "]").length)
      

      但是请注意,如果单选按钮不存在,则调用attr 将无效,也不会导致任何错误。因此,如果您的唯一目标是设置属性,则不需要 if 语句。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-23
        • 2015-02-19
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多