如何在javascript </div> </strong>中将带有特定类的<strong>标记动态添加到<div>

时间:2013-07-20 05:50:07

标签: javascript html asp.net

以下是div,会在调用javascript函数onmouseoveragent时显示。 我需要在div中显示姓名和电话号码。我设法动态显示名称,但不知道如何添加电话并在我的函数中指定其类。

<div id="visit">
    <div id="name" class="Class1">
        <strong class="Class2">Phone: 0123456789
        </strong> <%--need this to be added dynamically--%>
    </div>
</div>


<script language="javascript" type="text/javascript">
    function onmouseoveragent(e) {

        var hint = document.getElementById("visit");
        var inner = document.getElementById("name");

        inner.appendChild(inner.ownerDocument.createTextNode("I am a name!"))      
        while (inner.childNodes.length > 1) {
            inner.removeChild(inner.firstChild);
        }

        console.log(hint);
        hint.style.display = 'block';

        hint.style.top = Math.max(el.offsetTop - hint.offsetHeight, 0) + "px";
        hint.style.left = el.offsetLeft + "px";
    };
</script>

3 个答案:

答案 0 :(得分:1)

也许是这样的:

$('#name').append('<strong class="2">Phone: 3423423</strong>');

答案 1 :(得分:1)

尝试使用document.createElement()创建span元素

function onmouseoveragent(e) {

    var hint = document.getElementById("visit");
    var inner = document.getElementById("name");

    while (inner.childNodes.length > 0) {
        inner.removeChild(inner.firstChild);
    }
    inner.appendChild(inner.ownerDocument.createTextNode("I am a name!"))    ;

    var span = document.createElement('span');
    span.className = 'Class2';
    span.innerHTML = 'Phone: 123455';
    inner.appendChild(span)

    console.log(hint);
    hint.style.display = 'block';

    hint.style.top = Math.max(el.offsetTop - hint.offsetHeight, 0) + "px";
    hint.style.left = el.offsetLeft + "px";
};

答案 2 :(得分:1)

您是否考虑过使用innerHTML来设置'visit'元素的内容?

只需在字符串代码中构建您想要的内容,使用类,样式和所有内容进行构建,然后只需设置hint.innerHTML ='code'