javascript 从动态元素获取动态 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26180810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:37:19  来源:igfitidea点击:

Get dynamic Id from dynamic elements

javascriptjquery

提问by Agus Putra Dana

I have div element with dynamic Id.

我有带有动态 ID 的 div 元素。

<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>

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.

所有元素id(#parent 除外)都可由用户从输入字段编辑,因此 #parent 的最后一个子元素可能具有用户设置的新 ID。

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

我想4在它们的最后一部分检查具有最高编号 ( )的元素,id并且我想在下一个id.

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

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

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

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

My question is, how to get numberOfLastElement?

我的问题是,如何获得numberOfLastElement

采纳答案by E. Maggini

UPDATED UPDATE: FINAL VERSION OF FIDDLE

更新更新: FIDDLE 的最终版本

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);

Leaving the stuff below for historical info.

留下下面的东西以获取历史信息。

Here is a working JSFiddle

这是一个有效的 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);

回答by laaposto

Here is the logic:

这是逻辑:

Get all the elements what have id="elmnx"where x=1,2, etc. $("[id*='elmn']")

获取所有元素,id="elmnx"其中 x=1,2 等。$("[id*='elmn']")

Get the last of them. last()

得到他们中的最后一个。 last()

Get its id.attr('id')

获取它的id。attr('id')

Substring to get the number at the end. substring(4)

子字符串以获取末尾的数字。 substring(4)

Make it an int so that you can add +1. parseInt()

将其设为 int 以便您可以添加 +1。 parseInt()

Try:

尝试:

var numberOfLastElement=parseInt($("[id*='elmn']").last().attr('id').substring(4));

回答by PM 77-1

Something like this, assuming elmnprefix in all applicable IDs:

像这样,假设elmn所有适用的 ID 都有前缀:

function MaxElemNo() {
  var prefix = "elmn";
  var parent = document.getElementById("parent");
  var elements = parent.querySelectorAll("[id^='"+ prefix + "']");
  var lastElemNo = 0;
  for (var i=0; i<elements.length; i++) {
     var el = elements[i].id;
     var num = + el.substring(prefix.length, el.length);
     lastElemNo = Math.max(lastElemNo, num) 
  }
  return lastElemNo;  
}    
console.log(MaxElemNo());

JS Fiddle

JS小提琴