这是一个例子,我有一个带有单选按钮的表单,默认情况下会检查第一个:
<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#2时,如何让它自动检查两个而不是一个,当我没有任何octothorpe时它会默认为第一个?
提前致谢!
答案 0 :(得分:2)
我没有对此进行测试,但如果它不起作用,注释将有希望让你到达正确的位置
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);
}
因为它减少了重复的代码,并且只有在加载了复选框后才会出现间隔。
答案 1 :(得分:0)
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";