簡體   English   中英

頁面URL后的Octothorpe(標簽)更改輸入按鈕的默認值

[英]Octothorpe (hashtag) after page URL to change input button default

這是一個示例,我有一個帶有單選按鈕的表單,默認情況下第一個被選中:

<input type=radio name="input" id="one" checked>
<input type=radio name="input" id="two">
<input type=radio name="input" id="three">
<input type=radio name="input" id="four">

當我輸入index.html#two時,如何使其默認情況下自動檢查兩個而不是一個,而當我沒有八度時,它將默認為第一個?

提前致謝!

我還沒有測試過,但是如果它不起作用,那么注解有望將您帶到正確的位置

window.onload = function() {
        if(location.hash){//if the page's URL has an octothore part
            document.getElementById(location.hash.substr(1)).checked=true;
            //gets the checkbox's ID with the hash minus the octothorpe, and then checks it
        } else {
            //if there WASN't an octorthorpe
            document.getElementById('one').checked=true;
        }
    };

如果要保持狀態:

var interval = setInterval(function(){
    window.onload = function() {
        if(location.hash){//if the page's URL has an octothore part
            document.getElementById(location.hash.substr(1)).checked=true;
            //gets the checkbox's ID with the hash minus the octothorpe, and then checks it
        } else {
            //if there WASN't an octorthorpe
            document.getElementById('one').checked=true;
        }
    };
},50);

每當您希望它停止時,都可以使用interval.clear();

雖然為了代碼衛生,我還是建議:

var checkBoxBasedOnHash = function() {
    if(location.hash){//if the page's URL has an octothore part
        document.getElementById(location.hash.substr(1)).checked=true;
        //gets the checkbox's ID with the hash minus the octothorpe, and then checks it
    } else {
        //if there WASN't an octorthorpe
        document.getElementById('one').checked=true;
    }
};
window.onload = function() {
    checkBoxBasedOnHash();
    var interval = setInterval(checkBoxBasedOnHash,500);
}

因為它減少了重復的代碼,並肯定了該間隔僅在復選框已加載之后發生。

http://jsfiddle.net/Htqfw/1/

HTML:

<input type="radio" name="input" id="one" />
<input type="radio" name="input" id="two" />
<input type="radio" name="input" id="three" />
<input type="radio" name="input" id="four" />

JS(需要jQuery):

$(document).ready(function() {
    // Grab the hash from the URL
    var hash = location.hash;

    // Uncheck all the radio buttons
    $("input").attr("checked", null);

    // If there's a hash, check the matching radio button
    if (hash) {
        $("input" + hash).attr("checked", "checked");   
    }

    // If there's not, check the first radio button
    else {
        $("#one").attr("checked", "checked");
    }
});

要在jsfiddle中進行測試,請使用字符串替換location.hash以假裝您正在從URL中獲取哈希,例如:

var hash = "#three";

暫無
暫無

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

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