Javascript 带锚的复选框
我有大量的复选框链接到锚。单击复选框后,它将转到同一页面中的锚定。有没有更好的编码方法?我有大约50个复选框,因此此函数包含if语句。这是其中2个的工作代码:Javascript 带锚的复选框,javascript,html,Javascript,Html,我有大量的复选框链接到锚。单击复选框后,它将转到同一页面中的锚定。有没有更好的编码方法?我有大约50个复选框,因此此函数包含if语句。这是其中2个的工作代码: <input type="checkbox" id="1" value="1" onclick="return send();"/> <input type="checkbox" id="2" value="2" onclick="return send();"/> <script> function
<input type="checkbox" id="1" value="1" onclick="return send();"/>
<input type="checkbox" id="2" value="2" onclick="return send();"/>
<script>
function send(){
if(document.getElementById('1').checked){
window.location='#buy';
return false;
}
if(document.getElementById('2').checked){
window.location='#order';
return false;
}
//and this function goes on and on and on...
return true;
}
</script>
函数send(){
if(document.getElementById('1')。选中){
window.location='购买';
返回false;
}
if(document.getElementById('2')。选中){
window.location='#order';
返回false;
}
//这个函数持续不断。。。
返回true;
}
然后在我想要的页面上
<a name="buy"></a>
<a name="order"></a>
jQuery可以在这里让您省心:
$('input:checkbox').click(function () {
windows.location = $(this).attr('value');
});
只需确保更改锚定以匹配复选框即可。jQuery将在此处节省您的精力:
$('input:checkbox').click(function () {
windows.location = $(this).attr('value');
});
只需确保更改锚定以匹配复选框即可。HTML:
<input type="checkbox" id="checkbox1" value="1" data-target="buy" onclick=" send(this)">
<input type="checkbox" id="checkbox2" value="2" data-target="order" onclick="send(this)">
HTML:
如果将哈希添加到输入值中,如下所示:
你可以这样做
<script>
function send(input)
{
if(input.checked)
{
window.location = input.value;
return true;
}
return true;
}
</script>
函数发送(输入)
{
如果(输入。选中)
{
window.location=input.value;
返回true;
}
返回true;
}
如果这不起作用,您还可以将值切换为使用
ID
甚至自定义属性。任何适合您的选项。如果您将哈希添加到输入值中,如下所示:
你可以这样做
<script>
function send(input)
{
if(input.checked)
{
window.location = input.value;
return true;
}
return true;
}
</script>
函数发送(输入)
{
如果(输入。选中)
{
window.location=input.value;
返回true;
}
返回true;
}
如果这不起作用,您还可以将值切换为使用
ID
甚至自定义属性。随便你喜欢什么。请注意:在有效的HTML ID中,DOM元素不能以数字开头。@DarinDimitrov-在HTML5中可以。根据W3C,唯一的限制是其中没有空格。@j08691,当然,除了HTML5仍然是草稿之外。我说的是目前的标准,你可以考虑在复选框上使用单选按钮…否则,您可能会同时选中两个框,这可能会搞乱逻辑。还避免了“未检查”的场景。只需注意:在有效的HTML ID中,DOM元素不能以数字开头。@DarinDimitrov-在HTML5中可以。根据W3C,唯一的限制是其中没有空格。@j08691,当然,除了HTML5仍然是草稿之外。我说的是目前的标准,你可以考虑在复选框上使用单选按钮…否则,您可能会同时选中两个框,这可能会搞乱逻辑。也避免了“未检查”的场景。