簡體   English   中英

以編程方式檢查單選按鈕並非在所有瀏覽器中均有效

[英]Check radio button programmatically is not working in every browser

我需要根據URL中的路徑檢查單選按鈕。

$(document).ready(function () {
    function make_url() {
        var results_url = window.location.pathname.split("/");

        console.log(results_url); // ["", "tradeshows"]

        if (results_url[1] == "tradeshows") {
            $("#radio2").attr('checked', 'checked');
        } else if (results_url[2] == "tradeshows") {
            $("#radio2").attr('checked', 'checked');
        }
    }
});

<ul class="cd-filter-content cd-filters list" id="radioButtons" onChange="make_url();" style="display: block; padding:0px;">
    <li>
        <input type="radio" checked="" id="radio1" name="radioButton" value="" data-filter=".radio2" class="filter">
        <label for="radio1" class="radio-label">All Events</label>
    </li>
    <li>
        <input type="radio" id="radio2" name="radioButton" data-filter=".radio3" class="filter" value="1">
        <label for="radio2" class="radio-label" id="trade">Trade Shows</label>
    </li>
</ul>

該代碼在我的本地文件系統上運行正常,但在服務器上卻無法正常運行。

當我從控制台嘗試時,everytrhing可以正常工作:

$("#radio2").attr('checked','checked');

我也用香草JavaScript嘗試過:

document.getElementById('radio2').checked = true;
console.log(document.getElementById('radio2').checked); // false

我使用jQuery嘗試了另一種解決方案:

$('#radio2').prop('checked', true); // Uncaught TypeError: Cannot set property 'checked' of null

如果您遇到以下錯誤。

  Uncaught TypeError: Cannot set property 'checked' of null

然后,jQuery返回$('#radio2')為null,嘗試記錄$('#radio2')並在控制台中檢查它是否返回任何值。

導致錯誤的主要原因是,在執行函數時,id為radio2的元素不存在,如果在加載DOM之前執行該函數,則可能會出錯。

正如您提到的,它在本地計算機上運行良好,並且在服務器上不運行,服務器的響應時間比本地計算機慢一點,因此該元素不會被加載,並且在腳本加載之前。

請提供完整的代碼說明。

您的代碼實際上沒有任何意義。 函數make_url根據URL中給定的路徑名​​更改單選按鈕,但是僅在ul更改時才會觸發該功能,因為未實現此事件,因此永遠不會發生。

如果刪除不必要的make_url函數,則在文檔加載后(就緒)將立即設置單選按鈕:

$(document).ready(function () {
    var results_url = window.location.pathname.split("/");

    if (results_url[1] == "tradeshows" || results_url[2] == "tradeshows") {
        $("#radio2").prop('checked', true);
    }
});

<ul class="cd-filter-content cd-filters list" id="radioButtons" style="display: block; padding:0px;">
    <li>
        <input type="radio" checked="" id="radio1" name="radioButton" value="" data-filter=".radio2" class="filter">
        <label for="radio1" class="radio-label">All Events</label>
    </li>
    <li>
        <input type="radio" id="radio2" name="radioButton" data-filter=".radio3" class="filter" value="1">
        <label for="radio2" class="radio-label" id="trade">Trade Shows</label>
    </li>
</ul>

我還簡化了if語句,因為您選中了單選按鈕,所以路徑名的第二個或第三個部分等於“ tradeshows”。

暫無
暫無

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

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