jQuery 更新元素 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10219396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery update element id
提问by TTT
I am new to jQuery and would like to update an element's id. My approach is:
我是 jQuery 新手,想更新元素的 id。我的做法是:
select this element by its id
overwrite this id with a new value.
通过其 id 选择此元素
用新值覆盖此 ID。
would you mind telling me where my mistake is?
你介意告诉我我的错误在哪里吗?
Thanks!
谢谢!
Below is the HTML code:
下面是 HTML 代码:
<tr><th><label for="id_aerial_size_dist">Aerial size dist:</label></th><td><select name="aerial_size_dist" id="id_aerial_size_dist">
<option value="a">Very Fine to Fine</option>
<option value="b">Fine to Medium (EFED Default)</option>
<option value="c">Medium to Coarse</option>
<option value="d">Coarse to Very Coarse</option>
</select></td></tr>
jquery
查询
<script type="text/javascript" src=" ../stylesheets/jQuery-1.7.2.js"></script>
<script>
$(document).ready(function() {
$('#id_aerial_size_dist').attr('id', 'id_a');
});
</script>
回答by
Yes there is a way to change any attribute.
是的,有一种方法可以更改任何属性。
$('#your_element').attr('id','the_new_id');
Then again, this is definitely not recommended and it is also a pretty bad practice. You can however use classes for the same functionality.
再说一次,这绝对是不推荐的,这也是一种非常糟糕的做法。但是,您可以将类用于相同的功能。
$('.my_class').removeClass('my_class').addClass('normal_element');
If you tell me what you need to do I will help you out with a solution.
如果您告诉我您需要做什么,我会帮助您解决问题。
回答by Spencer Ruport
Personally I feel like the fact that jQuery doesn't have a specific setter method for the Id is very much intentional because you shouldn't be changing Ids around. Is there any reason you're not using classes? jQuery has a lot of useful functions and selectors for managing those with respect to an element and they can be used as both unique identifiers and group identifiers.
就我个人而言,我觉得 jQuery 没有针对 Id 的特定 setter 方法这一事实是非常有意的,因为您不应该更改 Id。你有什么理由不使用类吗?jQuery 有许多有用的函数和选择器来管理与元素相关的那些,它们既可以用作唯一标识符,也可以用作组标识符。