简体   繁体   English

JavaScript更新变量名称

[英]JavaScript update variable name

Sorry for the noob question as I just picked up javascript today. 对不起,对于noob问题,我今天才刚刚学习javascript。

I'm trying to create and delete div's with javascript buttons, and I have that working fairly well. 我正在尝试使用javascript按钮创建和删除div,并且效果很好。

However when I delete,for example, div #7, out of div 1-8 I need the text to change so that it doesn't look like 但是,当我从div 1-8中删除例如div#7时,我需要更改文本,以使其看起来不像

number: 1 1号
number: 2 2号
number: 3 数:3
number: 4 数:4
number: 5 数:5
number: 6 数:6
number: 8 数:8

This code adds the div at the end of the containing div xbox 此代码将div添加到包含div xbox的末尾

d1.insertAdjacentHTML('beforeend', '<div class="xbox" id ="xbox1'+numItems+'">Number:  '+countBox()+'</div>

this code counts the amount of boxes already 这段代码已经计算了箱子的数量

    function countBox()
{
    var numItems = $('.Cbox').length;
    return numItems;

}

I've thought about just taking the div and setting the inner-html. 我考虑过只使用div并设置inner-html。 But I figured I'd see if there is a better way to force the code to update the variable. 但是我想我是否可以找到一种更好的方法来强制代码更新变量。

So basically update the text of all the elements so they are in numbered order again after one is removed. 因此,基本上更新所有元素的文本,以使它们在删除后再次按编号顺序排列。

The numItems variable uses the length, so that's not an issue. numItems变量使用长度,所以这不是问题。

To update the text of the all the boxes you could do 要更新所有框的文本,您可以执行

$('.xbox').text(function(i) {
    return 'number: ' + (i+1);
});
  1. add text to your divs 向您的div添加文本
  2. add onclick functions and pass what div ie, onclick="myFunction(0)" 添加onclick函数并传递div,即onclick =“ myFunction(0)”
  3. Update the div text 更新div文字

    document.getElementById('yourID').innerHTML = "new text!"; document.getElementById('yourID')。innerHTML =“新文本!”;

full example 完整的例子

HTML HTML

<div id="div 1" onClick('update(0)');>some text</div>
<div id="div 2" onClick('update(1)');>some text</div>
<div id="div 3" onClick('update(2)');>some text</div>

* JavaScript * * JavaScript *

function update(column){
    //max number of divs from your example would be 8
    for(var i = column; i < MAX_NUMBER_DIV_HERE; i++){
        document.getElementById('div ' + i).innerHTML = i + "";
    }
}

Maybe you could use an ol instead with a custom format? 也许您可以使用自定义格式来代替ol ( More info ) 更多信息

Or if there is a small amount of numbers, nth-child with text-before ? 或者,如果数量较少,则nth-child text-before

#group div:nth-child(1):before { 
  content: "number: 1";
}

#group div:nth-child(2):before { 
  content: "number: 2";
}

Legacy support is not very good in both cases. 在这两种情况下,旧版支持都不是很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM