簡體   English   中英

當單選值=“否”且未選擇任何單選時,jQuery會識別頁面加載時單選按鈕的不正確狀態

[英]jQuery recognising incorrect state of radio buttons on page load when radio value=“No” and neither radio is selected

我在頁面上有單選按鈕,可根據其狀態在其他元素中添加或刪除css類。

默認情況下,將testclass添加到元素slave (即,頁面加載的HTML為:

<input type="radio" value="No" name="master" /> No
<input type="radio" value="Yes" name="master" /> Yes

<input type="text" name="a" id="slave" class="testclass" />

如果選擇“否”,則以下jQuery刪除該類

$("input[name$='master']").change(function(){
    if(this.value === 'No') {
          $('#slave').removeClass('testclass'); 
    } else {
         $('#slave').addClass('testclass');
    }
}); $("input[name$='master']").filter(':checked').change()

就頁面加載后在狀態之間來回移動而言,這種方法很好用,但是我在頁面加載時觸發了該函數,並且當未選擇檢查單選時,它會刪除該類。 (如果選中“是”,則可以)。

有趣的是,如果我撤消要求刪除類的條件為“是”(頁面加載仍然存在類的頁面加載),也很好。

我認為javascript可能會將沒有選擇的值等同於“否”,因此我嘗試了嚴格的相等性,但沒有區別。

有任何想法嗎?

我提出了一個小提琴供您考慮。 這是它的鏈接=> http://jsfiddle.net/6c7F2/

我認為回答這個問題的最好方法是使您了解此處提供的代碼的一些知識。 我將對此發表評論。

$( document ).ready(function(){ // this function is called once your page loads
    $("input[name$='master']").change(function(){
        //this function is not called until you click the radio buttons. 
        // Be careful to note that this function is never called on page load. 
        // You can test it in the fiddle I created
        if(this.value === 'No') {
            $('#slave').removeClass('testclass'); 
            // this alert in the fiddle is called only
            // when you click the radio buttons. Not on page load
            alert("It entered");
        } else {
            $('#slave').addClass('testclass');
        }
    }); 
    $("input[name$='master']").filter(':checked').change()
});

因此,請確保您要在頁面加載時執行的事物和檢查應不在$("input[name$='master']").change(function(){});

僅當您單擊單選按鈕而不是頁面加載時才觸發。

發生這種情況是因為您沒有在頁面加載上選擇任何值,但仍在觸發事件。

嘗試:

默認情況下,選中任何復選框。

<input type="radio" value="No" name="radios" checked="checked"/> No

要么

刪除此行

$("input[name$='master']").filter(':checked').change()

暫無
暫無

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

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