![](/img/trans.png)
[英]Why $(this).attr("id") get the old attribute after change it with javascript
[英]Why .attr does not change the attribute in each function?
我有一個非常簡單的腳本,應該更改鏈接的id
但是以某種方式無法正常工作。 這是代碼:
$(document).ready( function() {
$('mylinks').each(function(index) {
$(this).attr({
'id': 'mylink-'+index
});
});
});
<div class="mylinks">
<a href="http://www.google.com">google</a>
<a href="http://www.google.com">google2</a>
</div>
我嘗試將mylinks
更改為:
div.mylinks
div.mylinks a
但他們都不起作用。 我想念什么?
編輯
你們大多數人是對的。 我必須使用$('.mylinks a').each( ...
但問題是,我一直在尋找在RMB
- > Source
(其中不更新內容),而不是Inspect Element
。
編輯您的代碼並更改它:
$('.mylinks a')
選擇器mylinks
匹配頁面上的每個<mylinks>
元素。
要匹配屬於mylinks類成員后代的<a>
元素,您需要.mylinks a
。
您的代碼引用的是div,而不是鏈接。 哦,您在mylinks之前省略了句號,以正確表示div的類。
$('mylinks').each(
應該是$('.mylinks a').each(
這是一個jsFiddle示例 。
$('.mylinks a').each(function(index) {
$(this).attr({
'id': 'mylink-' + index
});
});
$('.mylinks a').each(function(){ ... });
您的選擇器不適合mylinks。 應該是$('.mylinks a').each()
class
選擇器以開頭.
。 更改代碼如下
$('.mylinks a').each(function(index) {
$(this).attr('id', 'mylink-'+index);
});
如果mylinks
是您提供給鏈接的類,則應編寫$('.mylinks')
您需要告訴它查看鏈接,而不僅僅是div。 這有效:
$(document).ready( function() {
$('.mylinks a').each(function(index) {
$(this).attr("id", "mylinks"+index);
});
});
$('mylinks')
將查找標記名稱為mylinks
元素。 可能是您應該使用的錯字.
用於類選擇器。 如果要選擇.mylinks
所有錨元素並在那里設置ID,則可以使用它。
$(document).ready( function() {
$('.mylinks a').each(function(index) {
$(this).attr({
'id': 'mylink-'+index
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.