将ID添加到动态创建的< div> [英] add id to dynamically created <div>

查看:94
本文介绍了将ID添加到动态创建的< div>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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;


推荐答案

如果我找到你的话,那就像

If I got you correctly, it is as easy as

cartDiv.id = "someID";

不需要jQuery。

No need for jQuery.

查看属性DOM元素

对于类,它是相同的:

cartDiv.className = "classes here";

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

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.

这篇关于将ID添加到动态创建的&lt; div&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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