【问题标题】:Getting null while accessing ids of dynamically generated HTML elements using javascript使用 javascript 访问动态生成的 HTML 元素的 id 时获取 null
【发布时间】:2018-09-11 07:46:44
【问题描述】:

使用 javascript 访问动态生成的 HTML 元素的 id 时获取 null

我正在尝试动态更改 div 的 ID 并删除附加到父 div 的按钮。当用户单击 ID 为 removeButton2 的按钮时,我希望 removeButton3 的 ID 更改为 removeButton2removeButton4 to removeButton3 的 ID。 即,在删除按钮 id 后应该更新。 但我得到空值。我不知道为什么。 这是我目前正在使用的代码:

var removeButtonCounter =0;
var divCounter=0;
var addButtonClickCount=0;
$('#AddButton').on('click',function() 
{ 
  removeButtonCounter++; divCounter++;addButtonClickCount++;

  $('#diplayContainerDiv').append('<div id="divQueryDisplay'+   divCounter +'"></div><div id="removeButtonDiv"><input type="button"  value="Remove" name="removeButton" id="removeButton'+  removeButtonCounter +'"> </div>');

  $("#removeButton" + removeButtonCounter).click(function() {
    var myId = this.id; 

  var lastChar = myId.slice(-1);
  valRemoveButtonClickLastChar = lastChar;
  $(this).remove();


   var i=valRemoveButtonClickLastChar;

   while(i<=addButtonClickCount)
   {
        document.getElementById(myId).id="removeButton"+i;  // null value is being passed

        document.getElementById("divQueryDisplay"+(parseInt(i)+1)).id="divQueryDisplay"+i;   // null value is being passed here    



      i++;



     }

   });
});

我收到以下消息:

Uncaught TypeError: Cannot set property 'id' of null

【问题讨论】:

  • 你能用 plunkr 或 codepen 分享你的代码吗
  • 分享html代码

标签: javascript jquery html css json


【解决方案1】:

你有:

var myId = this.id;

$(this).remove();

document.getElementById(myId).id=...

您正在删除带有myID 的元素,但随后您尝试再次选择它并分配给它。

我强烈建议不要像那样动态更改 ID,但如果你真的想要,一次迭代所有按钮可能会更容易:

document.querySelectorAll('div[id^="removeButton"]').forEach((removeButton, i) => {
  removeButton.id = 'removeButton' + i;
});

【讨论】:

  • 我没有收到任何错误。我想它对我有用。我怎样才能知道 id 是否更新?。
  • 我想在浏览器中随意使用Inspect
  • 你能解释一下你的代码吗?我的意思是每个 id 在 removeButton 的末尾都包含一个 int 值,而“removeButton.id”不包含相同的值。什么是 => ?在eclipse中用红色下划线
  • 它遍历 ID 以removeButton 开头的每个 div,并为每个 div 分配一个新 ID 'removeButton' + i,其中i 是循环的当前索引(从 0 开始)。 params =&gt; 是 ES2015 中的箭头函数,是 function(params) 的简写 - 如果您的编辑器无法识别它,您可能应该换一个新的编辑器。古代浏览器不支持,但是在写代码的时候被广泛使用(后面用Babel转译)。
猜你喜欢
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2020-03-02
  • 2019-01-10
  • 1970-01-01
  • 2021-09-09
  • 2013-12-09
  • 2012-10-19
相关资源
最近更新 更多