繁体   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