jQuery到普通的javascript

时间:2014-11-13 13:25:23

标签: javascript jquery append

我需要改变这一点jQuery ..

$(function() {

$("#breadcrump").append("<div id='oldsite'>Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a>  or<a href='mailto:info@brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a></div>");

});

对于常规的javascript,我已经研究了很多方面,但是我缺乏js知识似乎是我的绊脚石。

这是我到目前为止所提出的:

document.body.onload = addElement;

function addElement () { 
// create a new div element 
// and give it some content 
var newDiv = document.createElement("oldsite"); 
var newContent = document.createTextNode("Can't find what you're looking for? Try our old     website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a>  or<a     href='mailto:info@brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a>"); 
newDiv.appendChild(newContent); //add the text node to the newly created div. 
// add the newly created element and its content into the DOM 
var currentDiv = document.getElementById("breadcrump"); 
document.body.insertBefore(newDiv, currentDiv); 
}

3 个答案:

答案 0 :(得分:1)

为什么你不这样做:

document.getElementById("breadcrump").innerHTML += "<div id='oldsite'>Can't find what you're looking for? Try our old website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a>  or<a href='mailto:info@brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a></div>";

答案 1 :(得分:0)

我认为你应该添加以下内容:

1您正在创建div,而不是oldsite标记

var newDiv = document.createElement("div");

2你需要设置id

newDiv.id = "oldsite";

3您最初正在追加它:

document.body.insertBefore(newDiv, currentDiv.nextSibling);

http://jsfiddle.net/gf6gna1g/

答案 2 :(得分:0)

您可以做一些事情,最简单的方法就是将字符串设置为innerHTML

(function(){

    function addElem () {
        var newDiv = document.createElement("div");  //create div
        newDiv.id = "oldsite";  //sets id
        newDiv.innerHTML = "Can't find what you're looking for? Try our old     website: <a href='http://www.brooksbarn.co.uk'>Old Website (brooksbarn.co.uk)</a>  or<a     href='mailto:info@brooksbarn.co.uk?Subject=Brooksbarn.com Part Enquiry' target='_top'>E-Mail</a>";  //add html to new element
        document.getElementById("breadcrump").appendChild(newDiv);  //add it to the page
    }

    if (el.addEventListener) {
        window.addEventListener('load', addElem , false); 
    } else if (el.attachEvent)  {
        el.attachEvent('onload', addElem );
    }

}());