从动态元素获取动态ID [英] Get dynamic Id from dynamic elements

查看:112
本文介绍了从动态元素获取动态ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的div元素具有动态ID.

I have div element with dynamic Id.

<div id="parent">
    <div id="elmn1"></div>
    <div id="id-has-changed"></div>
    <div id="elmn3"></div>
    <div id="elmn4"></div>
    <div id="id-has-changed-by-user-from-input-field"></div>
</div>

所有元素id(#parent除外)都可以由用户在输入字段中进行编辑,因此#parent的最后一个子级可以由用户设置新的ID.

All element id (except #parent) are editable by user from an input field, so the last child of #parent may has new id set by user.

我想检查编号最大的元素(4)在其id的最后部分,我想在下一个id后面附加一个新元素.

I want to check the element with the highest number (4) at the last part of their id and I want to append a new element with the next id.

var nextId = "elmn" + (numberOfLastElement + 1);
var newElmn = document.createElement("div");

newElmn.id = nextId;
document.getElementById("parent").appendChild(newElmn);

在这种特殊情况下,新元素将具有id="elmn5".

In this paricular case the new element will has id="elmn5".

我的问题是,如何获得numberOfLastElement?

My question is, how to get numberOfLastElement?

推荐答案

更新后的更新: 最终版本的文本

var myEl = document.getElementById('parent').children;
var highest = null;
var idName= null;

if (myEl){

for (var ii=0;ii<myEl.length;ii++){

     var temp = myEl[ii].getAttribute('id');


    var intval = temp.match(/\d+/g)


    if (intval !=null){

        if(intval>highest){


            highest = intval;
            idName = temp;
        }


    }


  }

}

console.log(idName);

将下面的内容留在历史记录中.

这是正在运行的JSFiddle

var myEl = document.getElementById('parent').children;
var count = 0;
      if (myEl) {
            var match = 'elmn';
            for (var ii = 0; ii < myEl.length; ii++) {
                var temp = myEl[ii].getAttribute('id');
                if (temp.indexOf(match) == 0) {
                    count++
                }
            }
        }
        alert('count is ' + count);

这篇关于从动态元素获取动态ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆