关于jQuery的误解

时间:2014-12-21 15:35:32

标签: jquery

我是jQuery的新手。我对这一行有一个误解:

$('<div></div>').prependTo('body').attr('id', 'overlay');

我能否解释一下这部分内容:

$('<div></div>')

提前谢谢。

3 个答案:

答案 0 :(得分:7)

$('<div></div>')在内存中创建一个空的div元素;它实际上还没有将它添加到DOM中。 .prependTo('body')将其添加到页面顶部。

所以,代码是这样的:

$('<div></div>') // create an empty div element
    .prependTo('body') // add it at the top of the body
    .attr('id', 'overlay'); // give it the id overlay

顺便说一句,我们称之为&#34; line,&#34;不是&#34;行。&#34; :)

答案 1 :(得分:6)

它会将<div></div>添加到body

id = overlay标记中
<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

我们可以创建内容并一次将其插入多个元素中:

$( "<p>Test</p>" ).prependTo( ".inner" );

每个内部元素都会获得这个新内容:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    <p>Test</p>
    Hello
  </div>
  <div class="inner">
    <p>Test</p>
    Goodbye
  </div>
</div>

另一种解释的尝试

    whatever you write here                  will be added here  
$( "<p>Hello its me going to be added</p>" ).prependTo( ".inner" );

See this

答案 2 :(得分:5)

当你使用一些HTML标记调用jQuery时,它将使用document.createElement函数创建HTML元素,并将它们包装在jQuery对象中。它足够智能,如果您只是想创建一个标签,甚至不必关闭标签。例如

$('<div>')

会做同样的事情。但是,如果您想创建更复杂的HTML,可以使用.e.g。

$('<div><a href="http://www.google.com/">Google</a></div>')

将创建一个div,其中包含指向Google的链接