Jquery设置标签的属性'for'

时间:2022-11-19 15:21:12

I have a few labels that look like this :

我有一些看起来像这样的标签:

<input type="radio" name="gender" id="boy1">
<label id="lblboy1" for="boy1" class="gender"></label>
<input type="radio" name="gender" id="boy2">
<label id="lblboy2" for="boy2" class="gender"></label>

How can I use jquery to change the value of the "for" attribute?

如何使用jquery更改“for”属性的值?

What I tried is something like this:

我尝试的是这样的:

  $("#lblboy1").attr('for', 'boy3');

But it is not working.

但它没有用。

2 个解决方案

#1


1  

Seems to work just fine. Are you sure jQuery is loaded properly and that you're executing the code after the DOM is ready?

似乎工作得很好。你确定jQuery是否正确加载并且在DOM准备好之后你正在执行代码?

Here's an example of using jQuery to change the label of Boy 1 to select the Boy 3 input:

这是使用jQuery更改Boy 1标签以选择Boy 3输入的示例:

$(document).ready(function(){
  $("#lblboy1").attr("for", "boy3");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="gender" id="boy1">
<label id="lblboy1" for="boy1" class="gender">Boy 1</label>
<input type="radio" name="gender" id="boy2">
<label id="lblboy2" for="boy2" class="gender">Boy 2</label>
<input type="radio" name="gender" id="boy3">
<label id="lblboy3" for="boy3" class="gender">Boy 3</label>

#2


1  

Make sure your jquery is inside $(document).ready function or similar.

确保你的jquery在$(document).ready函数或类似内容中。

#1


1  

Seems to work just fine. Are you sure jQuery is loaded properly and that you're executing the code after the DOM is ready?

似乎工作得很好。你确定jQuery是否正确加载并且在DOM准备好之后你正在执行代码?

Here's an example of using jQuery to change the label of Boy 1 to select the Boy 3 input:

这是使用jQuery更改Boy 1标签以选择Boy 3输入的示例:

$(document).ready(function(){
  $("#lblboy1").attr("for", "boy3");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="gender" id="boy1">
<label id="lblboy1" for="boy1" class="gender">Boy 1</label>
<input type="radio" name="gender" id="boy2">
<label id="lblboy2" for="boy2" class="gender">Boy 2</label>
<input type="radio" name="gender" id="boy3">
<label id="lblboy3" for="boy3" class="gender">Boy 3</label>

#2


1  

Make sure your jquery is inside $(document).ready function or similar.

确保你的jquery在$(document).ready函数或类似内容中。

相关文章