亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為動態創建的元素指定一個 id

為動態創建的元素指定一個 id

HUWWW 2023-09-11 15:14:08
我已經在js中創建了一個發布系統,對于我在無序列表中創建的元素,我想為其分配一個id(例如<p id="Hello">...</p>)。使用發布系統(在 js 中),新創建的 html 元素應被賦予一個 id。js代碼:function publish() {    var title = document.getElementById("title").value;    var description = document.getElementById("description").value;    var para = document.createElement("h3");    var node = document.createTextNode(title);    para.appendChild(node);    var element = document.getElementById("posts");    element.appendChild(para);    var para = document.createElement("small");    var node = document.createTextNode("--".concat(description, "--"));    para.appendChild(node);    var image = document.getElementById("posts");    element.appendChild(para)    var image = document.createElement("img");    var imageInput = document.getElementById('image-file');    image.src = URL.createObjectURL(imageInput.files[0]);    image.style.height = '100px';    image.style.width = '100px';    para.appendChild(image);}html代碼:    <button id="publish-button" onclick="publish();">Publish</button>        <p>Title</p>        <input class="Title" id="title"></input>        <p>Description</p>        <input class="Description" id="description"></input>        <p>Images</p>        <input id="image-file" type="file" /><ul id="posts">    </ul>
查看完整描述

1 回答

?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

這會將 id='1' 添加到小標簽,并且每次添加圖像時都會增加 1。只需為 id 聲明一個全局,然后設置 para.id = id


var id=0;

function publish() {

    var title = document.getElementById("title").value;

    var description = document.getElementById("description").value;

    var para = document.createElement("h3");

    var node = document.createTextNode(title);

    para.appendChild(node);


    var element = document.getElementById("posts");

    element.appendChild(para);


    var para = document.createElement("small");

    id++;

    para.id=id;

    var node = document.createTextNode("--".concat(description, "--"));

    para.appendChild(node);


    var image = document.getElementById("posts");

    element.appendChild(para)

    var image = document.createElement("img");

    var imageInput = document.getElementById('image-file');

    image.src = URL.createObjectURL(imageInput.files[0]);

    image.style.height = '100px';

    image.style.width = '100px';


    para.appendChild(image);

}

<button id="publish-button" onclick="publish();">Publish</button>

        <p>Title</p>

        <input class="Title" id="title"></input>


        <p>Description</p>

        <input class="Description" id="description"></input>


        <p>Images</p>

        <input id="image-file" type="file" />

<ul id="posts">

    </ul>


查看完整回答
反對 回復 2023-09-11
  • 1 回答
  • 0 關注
  • 83 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號