gpt4 book ai didi

javascript - 如何替换div中的数字?

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:30 24 4
gpt4 key购买 nike

使用下面的代码,我得到了“id”的值(大约 35),然后给每个“id”加 1,所以 1 就是 2,依此类推。我的股票在哪里,它是关于如何替换 html 中的那个 ID 号。

这是用于获取每个 id 的值的代码,然后我将它们插入一个数组,然后我运行另一个“for 循环”为每个值加 1,但我不知道如何将它们返回到html。

var x = document.getElementsByClassName('p-divs');

var portfolio = new Array;

for (var i = 0; i < x.length; i++)
{
var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
portfolio.push(y);
}

console.log(portfolio);

var portfolio2 = new Array;

for (var i = 0; i<portfolio.length; i++)
{
var newId;
newId = parseInt(portfolio[i]) + 1;

portfolio2.push(newId);
}

console.log(portfolio2);
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 p-divs" id="1">
<div class="portfolio">
<center>
<img src="images/pace.png" width="230" height="190" alt="" class="img-responsive">
</center>
</div>
</div>

最佳答案

由于您使用的是 jQuery 库,因此代码可能比您目前使用的 .each() 简单。 方法:

$('.p-divs').each(function(){
$(this).attr('id', Number(this.id) + 1);
});

或更短的使用 .attr() 方法回调如:

$('.p-divs').attr('id', function(){
return Number(this.id) + 1;
});

更清晰的版本可能是:

$('.p-divs').each(function(){
var current_id = Number(this.id); //Get current id
var new_id = current_id + 1; //Increment to define the new one

$(this).attr('id', new_id); //Set the new_id to the current element 'id'
});

希望这对您有所帮助。

$(function(){
$('.p-divs').attr('id', function(){
return Number(this.id) + 1;
});

//Just for Debug
console.log( $('body').html() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="p-divs" id="1">
<div class="portfolio">
<center>Image 1</center>
</div>
</div>
<div class="p-divs" id="2">
<div class="portfolio">
<center>Image 2</center>
</div>
</div>
<div class="p-divs" id="3">
<div class="portfolio">
<center>Image 3</center>
</div>
</div>
<div class="p-divs" id="4">
<div class="portfolio">
<center>Image 4</center>
</div>
</div>

关于javascript - 如何替换div中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com