簡體   English   中英

如果沒有“ checked”屬性,如何檢查復選框的狀態?

[英]How to check state of a checkbox if it doesn't have “checked” attribute?

我正在嘗試使用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

但是我仍然不能這樣做,因為我的復選框沒有“ checked”屬性。

如果使用硒,我檢查元素的“ Selected”屬性,它也不會告訴我復選框狀態的真相。

有什么建議嗎? 提前致謝。

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

在jQuery中,您應該使用.prop而不是attribute

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

我們可以使用以下代碼在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>

您可以使用此代碼選中和取消選中該復選框。

if(checkBox1.getAttribute(“ checked”)!= null)//如果選中

checkBox1.click(); //取消選中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM