Javascript 将 id 添加到动态创建的 <div>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3319683/
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-08-23 04:08:43  来源:igfitidea点击:

add id to dynamically created <div>

javascriptjquery

提问by user357034

I have the following JavaScript that creates a div and then appends it to the body and then inserts some dynamically generated HTML into it. cartDiv = document.createElement('div'); This div I would like to add an id and/or a class to it. If possible both Jquery and JavaScript answers would be great.

我有以下 JavaScript,它创建一个 div,然后将它附加到正文,然后将一些动态生成的 HTML 插入其中。carDiv = document.createElement('div'); 这个 div 我想给它添加一个 id 和/或一个类。如果可能,Jquery 和 JavaScript 的答案都会很棒。

var cartHTML = '<div class="soft_add_wrapper" onmouseover="setTimer();">';
cartHTML += '<div class="soft_add_header_shadow">';
cartHTML += '<div class="soft_add_header"><span class="soft_add_span">Added to cart</span><a href="" class="close_btn" onclick="hideCart(); return false;">Close</a></div></div>'
cartHTML += '<div class="soft_add_content_shadow"><div class="soft_add_content_wrapper">';
cartHTML += '<div class="soft_add_content_area" onscroll="setTimer();"><table class="cart_table" cellpadding="0" cellspacing="0" border="0">';
if (cartLength != 0) {
    cartHTML += cartLoop(index, cartLength);
    if (index != 0) {
        cartHTML += cartLoop(0, index);
    }
    if (discountTotal != "0") {
        var discountProduct = {
        ProductName: "Discount(s)",
        ProductPrice: '<span style="color:red">' + discountTotal + '</span>'
        }
        cartHTML += getLineItemHTML(discountProduct);
    }
}
cartHTML += '</table></div><div class="soft_add_sub_total"><div class="number_of_items">' + quantity + ' items in cart</div>';
cartHTML += '<div class="sub_total">';
cartHTML += 'Subtotal: <span class="sub_total_amount">' + cartTotal + '</span>';
cartHTML += '</div>';
 cartHTML += '</div><div class="soft_add_action_area"><a href="/ShoppingCart.asp" class="check_out">Check Out</a>';
cartHTML += '<a href="" class="continue_shopping" onclick="hideCart(); return false;">Continue shopping</a></div></div></div></div>';
if (cartDiv == null) {
    cartDiv = document.createElement('div');
    document.body.appendChild(cartDiv);
}
cartDiv.innerHTML = cartHTML;

回答by Felix Kling

If I got you correctly, it is as easy as

如果我猜对了,那就很简单了

cartDiv.id = "someID";

No need for jQuery.

不需要 jQuery。

Have a look at the properties of a DOM Element.

查看DOM 元素属性

For classes it is the same:

对于类,它是相同的:

cartDiv.className = "classes here";

But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.

但请注意,这将覆盖已经存在的类名。如果要动态添加和删除类,则必须使用 jQuery 或编写自己的函数来执行某些字符串替换。

回答by PCoughlin

You can add the id="MyID123"at the start of the cartHTML text appends.

您可以id="MyID123"在cartHTML 文本附加的开头添加。

The first line would therefore be:

因此,第一行是:

var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';

-OR-

-或者-

If you want the ID to be in a variable, then something like this:

如果您希望 ID 位于变量中,则如下所示:

    var MyIDvariable = "MyID123";
    var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */

回答by Praveen Kumar K R

Use Jquery for append the value for creating dynamically

使用 Jquery 追加动态创建的值

eg:

例如:

var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image" 
style="width:125px; height:125px">';

$("#userphoto").append(user_image1.replace("{@user_image}","http://127.0.0.1:50075/webhdfs/v1/PATH/"+user_image+"?op=OPEN")); 

HTML :

HTML :

<div id="userphoto">

回答by Sandro

Not sure if this is the best way, but it works.

不确定这是否是最好的方法,但它有效。

if (cartDiv == null) {
    cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
    document.body.appendChild(cartDiv);
}

回答by Corentin

Here is an example of what I made to created ID's with my JavaScript.

这是我使用 JavaScript 创建 ID 的示例。

function abs_demo_DemandeEnvoyee_absence(){

    var iDateInitiale = document.getElementById("abs_t_date_JourInitial_absence").value; /* On récupère la date initiale*/
    var iDateFinale = document.getElementById("abs_t_date_JourFinal_absence").value;     /*On récupère la date finale*/
    var sMotif = document.getElementById("abs_txt_motif_absence").value;                 /*On récupère le motif*/  
    var iCompteurDivNumero = 1;                                                         /*Le compteur est initialisé à 1 parce que la div 1 existe*/
    var TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; //Boléenne, renvoie false si la div existe déjà
    var NewDivCreation = "";                                                            /*Initialisée en string vide pour concaténation*/
    var NewIdCreation;                                                                  /*Utilisée pour créer l'id d'une div dynamiquement*/
    var NewDivVersHTML;                                                                 /*Utilisée pour insérer la nouvelle div dans le html*/


    while(TestDivVide == false){                                                        /*Tant que la div pointée existe*/
        iCompteurDivNumero++;                                                           /*On incrémente le compteur de 1*/
        TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; /*Abs_autorisation_1_ est écrite en dur.*/   
    }

    NewIdCreation = "abs_Autorisation_"+iCompteurDivNumero+"_absence"                   /*On crée donc la nouvelle ID de DIV*/

                                                                                        /*On crée la nouvelle DIV avec l'ID précédemment créée*/
    NewDivCreation += "<div class=\"abs_AutorisationsDynamiques_absence\" id=\""+NewIdCreation+"\">Votre demande d'autorisation d'absence du <b>"+iDateInitiale+"</b> au <b>"+iDateFinale+"</b>, pour le motif suivant : <i>\""+sMotif+"\"</i> a bien été <span class=\"abs_CouleurTexteEnvoye_absence\">envoyée</span>.</div>";

    document.getElementById("abs_AffichagePanneauDeControle_absence").innerHTML+=NewDivCreation; /*Et on concatenne la nouvelle div créée*/ 

    document.getElementById("abs_Autorisation_1_absence").style.display = 'none'; /*On cache la première div qui contient le message "vous n'avez pas de demande en attente" */

}

Will provide text translation if asked. :)

如果要求,将提供文本翻译。:)

回答by Stefan Kendall

You'll have to actually USE jQuery to build the div, if you want to write maintainable or usable code.

如果您想编写可维护或可用的代码,则必须实际使用 jQuery 来构建 div。

//create a div
var $newDiv = $('<div>');

//set the id
$newDiv.attr("id","myId");