结合<a> tag and a <label>

时间:2019-03-14 11:39:42

标签: html

I can't make a and an tag combine on HTML. I'm trying to have text that when you click on it both click a checkbox and also lead you somewhere on the page i've tried to make it like that:

<a href"#somewhere"><label for"somecheckbox">Some Text</label></a>

But only the label worked, then I tried it like that:

  <label for"somecheckbox"><a href"#somewhere">Some Text</a></label>

But then only the link works, is there any way in which we can use both?

4 个答案:

答案 0 :(得分:2)

问题是您要嵌套interactive content。这是您无法通过W3C规范执行的操作。请参见a tag,例如其允许的内容。

您将需要使用javascript来实现所需的功能。

这是一个简单的例子:

var links = document.querySelectorAll("[data-for]");

//Set Event Handler
for(var i = 0; i < links.length; i++) {
  links[i].addEventListener("click", function(event){
    //Get the target cb from the data attribute
    var cbTarget = this.dataset.for;
    //Check the cb
    document.getElementById(cbTarget).checked = true;
  });
}
.head {margin-bottom: 100vh;}
<div class="head">
<a href="#aTarget" data-for="aCheckBox">Click Me</a> <input type="checkbox" id="aCheckBox" />
</div>
<div id="aTarget">A Target</div>

答案 1 :(得分:0)

无法同时使用标签进行导航和切换复选框,请在选中复选框时使用javascript专注于目标。

document.getElementById("somecheckbox").addEventListener("change", function(e){
  // see if it is checked
  if(e.target.checked){
    // and focus to specific id
    document.getElementById("somewhere").focus();
  }
})

答案 2 :(得分:0)

当您单击标签时,两个复选框都被选中,并且转到一个位置。

const label = document.querySelector('[for=checkbox]');
const checkBox = document.querySelector('[name=checkbox]');
label.addEventListener('click', function (){
  checkBox.setAttribute("checked", "true");
  location.href = "#location";  
});
#location {
  position: absolute;
  bottom: -100px;
}
<label for="checkbox">
<input type="checkbox" name="checkbox"/>
Check
</label>

<p id="location"> Some location </p>

答案 3 :(得分:-1)

<!DOCTYPE html>
<html>
<body>
<script>
function Redirect(){
	if (document.getElementById('vehicle3').checked) 
  {
      window.location = "https://www.tutorialspoint.com";
  }
 }
</script>
<h1>Show checkboxes:</h1>

  <input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
  <input type="checkbox" name="vehicle3" id='vehicle3' value="Boat" onClick='Redirect();'> I have a boat<br><br>
  <input type="submit" value="Submit">

</body>
</html>

此解决方案是每个人都建议使用JavaScript可以轻松解决的问题。只要您点击第三个复选框,它就会将您重定向到新网页