【问题标题】:How to check state of a checkbox if it doesn't have "checked" attribute?如果没有“checked”属性,如何检查复选框的状态?
【发布时间】:2016-12-24 02:10:21
【问题描述】:

我正在尝试使用 Selenium Webdriver 或 Javascript 检查复选框的状态,但经过大量研究我仍然无法做到。

我的问题是:复选框没有“选中”属性:

<input type="checkbox" name="site[new_sign_up]" id="site_new_sign_up" value="1">

对于常规的普通复选框,我使用下一个字符串来检测复选框是否被选中:

if (checkbox.GetAttribute("checked") != null && checkbox.GetAttribute("checked").Equals("true"))

我知道可以用 JS 来完成:

$get("isAgeSelected").checked == true

但我仍然不能这样做,因为我的复选框没有“选中”属性。

如果使用 selenium 我检查元素的“已选择”属性,它也不会告诉我复选框状态的真相。

有什么建议吗?提前致谢。

【问题讨论】:

  • 你使用 jQuery 吗?
  • 我想你只需要检查checkbox.GetAttribute("checked") != null就行了
  • 只使用checkbox.checked它是原生JS,不依赖于checked属性
  • WebElement 在 java 中有一个 isSelected() 方法,如果选中了复选框或单选,则返回 true。否则为假。

标签: javascript jquery selenium checkbox selenium-webdriver


【解决方案1】:

您可以使用此代码选中和取消选中复选框。

if(checkBox1.getAttribute("checked") != null) // 如果选中

checkBox1.click(); //取消选中它

【讨论】:

    【解决方案2】:

    DOM API 为所有输入类型提供了一个检查属性,无论它们是否具有检查属性(或者即使它们不可检查,即文本元素)

    不应依靠存在的已选中属性来确定复选框是否已选中。

    var x = document.createElement('input');
    console.log(x.checked); //false
    x.type = 'checkbox';
    console.log(x.checked); //false
    x.checked = true;
    console.log(x.checked); //true
    console.log(x); //<input type="checkbox"> - see? no checked attribute, yet it is still checked
    

    【讨论】:

    • 非常感谢!这工作得很好。似乎是最好的答案)
    • @Adman,如果我确实需要为此使用 IWebDriver 元素,您不知道如何处理吗?所以我不知道它的 CssSelector,这就是为什么我不能使用 JS 的“getElementById”方法。
    • @Adam,他不依赖checked 属性。 checkbox.GetAttribute("checked") 方法如果存在则返回 checked 属性,如果不存在则返回属性。
    【解决方案3】:

    我们可以使用下面的代码在js中实现

    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $('#site_new_sign_up').click(function(){
        if($('#site_new_sign_up').prop('checked')) {
             console.log('Checked');
        } else {
            console.log('Not Checked');
        }
     })
    });
    </script>
    
    <body>
      <input type="checkbox" name="site[new_sign_up]" id="site_new_sign_up" value="1">
     </body>
    </html>
    

    【讨论】:

      【解决方案4】:

      在 jquery 中你应该使用 .prop 而不是属性

      $('input').prop('checked') //true-false meaning the checkbox is checked or not
      

      【讨论】:

        猜你喜欢
        • 2019-05-14
        • 2020-09-29
        • 2017-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-16
        • 1970-01-01
        • 2014-06-27
        相关资源
        最近更新 更多