将 id 添加到 DIV。 Jquery
Adding id's to a DIV. Jquery
我想将一系列 ID 添加到具有相同 类 的 div。
样本:
<div class="sample" id="id_1"></div>
<div class="sample" id="id_2"></div>
<div class="sample" id="id_3"></div>
<div class="sample" id="id_4"></div>
这是我的项目linkenter link description here
我正在使用此代码。
$(document).ready(function(){
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
如果我使用 .on(click)
触发,这显然有效
像这样:
$(document).ready(function(){
$('#primary').on( "click", '.gchoice_3_10_1', function(i){
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
});
});
但问题是,我希望在页面加载后添加 ID,而不是在单击事件时添加。
我有以下建议:
- 在您的示例中,缺少右括号和圆括号。
- 我还假设您必须确保
fpd-item
在加载时存在。
所以这应该有效:
$(document).ready(function(){
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
// Added just to ssho
$(this).text('id_'+(i+1));
});
});
我已经在这里试过了并且有效:
最短的方法是使用 attr(prop,function)
。这不会解决为什么你的代码不工作的原因,除了你在显示的代码中缺少一组大括号,但它看起来更干净
$(function(){
$('.fpd-item').attr('id',function(i){
return 'id_'+(i+1);
});
});
终于找到解决方案:
$(window).bind("load", function() {
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
});
通过重播 $( document ).ready(function() { whith $(window).bind("load", function() {
$(window).bind("load", function() {
// content here
});
我想将一系列 ID 添加到具有相同 类 的 div。
样本:
<div class="sample" id="id_1"></div>
<div class="sample" id="id_2"></div>
<div class="sample" id="id_3"></div>
<div class="sample" id="id_4"></div>
这是我的项目linkenter link description here
我正在使用此代码。
$(document).ready(function(){
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
如果我使用 .on(click)
触发,这显然有效
像这样:
$(document).ready(function(){
$('#primary').on( "click", '.gchoice_3_10_1', function(i){
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
});
});
但问题是,我希望在页面加载后添加 ID,而不是在单击事件时添加。
我有以下建议:
- 在您的示例中,缺少右括号和圆括号。
- 我还假设您必须确保
fpd-item
在加载时存在。
所以这应该有效:
$(document).ready(function(){
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
// Added just to ssho
$(this).text('id_'+(i+1));
});
});
我已经在这里试过了并且有效:
最短的方法是使用 attr(prop,function)
。这不会解决为什么你的代码不工作的原因,除了你在显示的代码中缺少一组大括号,但它看起来更干净
$(function(){
$('.fpd-item').attr('id',function(i){
return 'id_'+(i+1);
});
});
终于找到解决方案:
$(window).bind("load", function() {
$('.fpd-item').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
});
通过重播 $( document ).ready(function() { whith $(window).bind("load", function() {
$(window).bind("load", function() {
// content here
});