JavaScript将ID属性添加到另一个创建的元素 [英] JavaScript Adding an ID attribute to another created Element

查看:103
本文介绍了JavaScript将ID属性添加到另一个创建的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一些代码将执行以下操作。该代码创建一个元素 p,然后将其附加到HTML中的 div。我希望刚创建的 p具有唯一的标识符(ID)并设置ID的名称。因此,稍后当用户想要删除最后创建的元素时,它将能够获取ID,以便可以删除Child。以下是代码:

I have some code here that will do the following. The code creates an element "p" then I append it to a "div" in the HTML. I would like that "p" I just created have an unique identifier (ID) and set the name of the ID. So later on when the user wants to delete the last created element it will be able to get the ID so it can removeChild. Here is the code:

JavaScript:

JavaScript:

  var $ = function (id)
  {
      return document.getElementById(id);
  }

  function ShowResponse ()
  {
  var myResponse = $("myresponse").value;

  var myPara = document.createElement("p");
  var myDiv = $("mydiv");
  myDiv.appendChild(myPara);

  var myID = document.createElement("id");
  myID.setAttribute("value", ID)

  var myText = document.createTextNode(myResponse);
  myPara.appendChild(myText);
  }

  function RemoveResponse ()
  {

  }

  window.onload = function ()
  {
      $("showresponse").onclick = ShowResponse;
      $("removeresponse").onclick = RemoveResponse;
  }

HTML:

  <body>
  <div id="mydiv">
  <h1>Practice</h1>

  <p>Hi There</p>
  <p>How are you?</p>

  <p>
<input type="text" id="myresponse">
<br><input type="button" id="showresponse" value="Show Response">
<input type="button" id="removeresponse" value="Remove Response">
  </p>

  <hr>
 </div>

 </body>


推荐答案

由于id是属性,因此请勿创建id元素,只需执行以下操作:

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

这篇关于JavaScript将ID属性添加到另一个创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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