2010-08-18 2 views
1
var theNewParagraph = document.createElement('p'); 
    var theBoldBit = document.createElement('b'); 
    var theBR = document.createElement('br'); 

    theNewParagraph.setAttribute('title','The test paragraph'); 
    var theText1 = document.createTextNode('This is a sample of some '); 
    var theText2 = document.createTextNode('HTML you might'); 
    var theText3 = document.createTextNode('have'); 
    var theText4 = document.createTextNode(' in your document'); 

    theBoldBit.appendChild(theText2); 
    theBoldBit.appendChild(theBR); 
    theBoldBit.appendChild(theText3); 

    theNewParagraph.appendChild(theText1); 
    theNewParagraph.appendChild(theBoldBit); 
    theNewParagraph.appendChild(theText4); 

    document.getElementById('someElementId').appendChild(theNewParagraph); 

Кроме того, может ли кто-нибудь помочь мне, объяснив это?Как я могу запустить это в HTML?

+2

... там был вопрос там? :) –

+0

@Nick Craver Что ?? – Gladiator

ответ

2

Вот подходящий испытательный жгут. Вставьте следующий код в новый файл .html:

<html><head><script language="javascript"><!--// your javascript here: 
function _onload() 
{ 
    var theNewParagraph = document.createElement('p'); 
    var theBoldBit = document.createElement('b'); 
    var theBR = document.createElement('br'); 

    theNewParagraph.setAttribute('title','The test paragraph'); 

    var theText1 = document.createTextNode('This is a sample of some '); 
    var theText2 = document.createTextNode('HTML you might'); 
    var theText3 = document.createTextNode('have'); 
    var theText4 = document.createTextNode(' in your document'); 

    theBoldBit.appendChild(theText2); 
    theBoldBit.appendChild(theBR); 
    theBoldBit.appendChild(theText3); 

    theNewParagraph.appendChild(theText1); 
    theNewParagraph.appendChild(theBoldBit); 
    theNewParagraph.appendChild(theText4); 

    document.getElementById('someElementId').appendChild(theNewParagraph); 
} 
//--></script></head><body onload='_onload()' id='someElementId'></body></html> 
+0

// Для ват это используется? Если я хочу отобразить таблицу с именем «Сотрудник» из моей БД в mysql. Wat должен ли я делать? Как использовать dom? Пожалуйста, объясните .. – Gladiator

+0

@gladiator: * onload *, когда используется в элементе body, выполняет содержимое атрибута как выражение javascript, когда документ полностью загружен браузером. Что касается вашего второго вопроса, это, вероятно, лучше всего для другой темы. Кроме того, вам намного лучше начать с некоторых javascript-руководств, а не прыгать в глубоком конце. http://google.com/search?q=javascript+tutorial –

4

Поместите вышеуказанное в <script type="text/javascript"> в нижней части страницы и убедитесь, что в вашем документе есть <div id="someElementId">.

Что он делает, это создание нового тега <p>, <b> и <br>. Затем он устанавливает заголовок в параграфе, добавляет текст ко всем тегам и, наконец, добавляет весь беспорядок в элемент с идентификатором #someElementId.

Вы можете увидеть его in action here.

5

Что у вас есть фрагмент кода JavaScript. Я добавил комментарии к коду, чтобы объяснить каждый раздел:

// Create 3 elements, a <p>, a <b> and a <br> 
var theNewParagraph = document.createElement('p'); 
var theBoldBit = document.createElement('b'); 
var theBR = document.createElement('br'); 

// Set the title attribute of the <p> element we created 
theNewParagraph.setAttribute('title','The test paragraph'); 

// Create 4 "text nodes", these appear as text when added to elements 
var theText1 = document.createTextNode('This is a sample of some '); 
var theText2 = document.createTextNode('HTML you might'); 
var theText3 = document.createTextNode('have'); 
var theText4 = document.createTextNode(' in your document'); 

/* Add the second text node, the <br> element and the 3rd text node to the 
    <b> element we created */ 
theBoldBit.appendChild(theText2); 
theBoldBit.appendChild(theBR); 
theBoldBit.appendChild(theText3); 

/* Add the first text node, the <b> element and the 4th text node to the 
    <p> element we created. All nodes are now descendants of the <p> */ 
theNewParagraph.appendChild(theText1); 
theNewParagraph.appendChild(theBoldBit); 
theNewParagraph.appendChild(theText4); 

/* Finally, add the <p> element to an element with an id attribute of 
    someElementId, so we can see all the content on our page */ 
document.getElementById('someElementId').appendChild(theNewParagraph); 

Результат следующий HTML как содержание someElementId:

<p title="The test paragraph">This is a sample of some <b>HTML you might<br> 
    have</b> in your document</p> 

Другие объяснили, как добавить этот скрипт ваш документ, используя элемент <script>.

1

Как запустить:

<head> 
    <script type="text/javascript"> 
     function CreateTestParagraph() { 
      var theNewParagraph = document.createElement('p'); 
      var theBoldBit = document.createElement('b'); 
      var theBR = document.createElement('br'); 

      theNewParagraph.setAttribute('title','The test paragraph'); 
      var theText1 = document.createTextNode('This is a sample of some '); 
      var theText2 = document.createTextNode('HTML you might'); 
      var theText3 = document.createTextNode('have'); 
      var theText4 = document.createTextNode(' in your document'); 

      theBoldBit.appendChild(theText2); 
      theBoldBit.appendChild(theBR); 
      theBoldBit.appendChild(theText3); 

      theNewParagraph.appendChild(theText1); 
      theNewParagraph.appendChild(theBoldBit); 
      theNewParagraph.appendChild(theText4); 

      document.getElementById('someElementId').appendChild(theNewParagraph); 
     } 
    </script> 
</head> 
<body onload="CreateTestParagraph()"> 
    <div id="someElementId"></div> 
</body> 

Ваш метод CreateTestParagraph создает следующее содержание HTML динамически:

<p title="The test paragraph">This is a sample of some <b>HTML you might<br>have</b> in your document</p> 

и положить, что содержимое в элемент someElementId.

Ссылки по теме:
createElement method,
createTextNode method,
appendChild method,
getElementById method,
onload event

Смежные вопросы