jQuery jquery追加新的div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7057119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:21:21  来源:igfitidea点击:

jquery append new div

jqueryappendappendto

提问by fish man

I want do hover in a div, append a new div in body part, some code here.

我想在一个 div 中悬停,在正文部分附加一个新的 div,这里有一些代码。

but my problem is: now it is not append a new div but replace the first all html. Where is the problem? Thanks. http://jsfiddle.net/U7QqB/3/

但我的问题是:现在不是追加新的 div 而是替换第一个全部 html。问题出在哪儿?谢谢。 http://jsfiddle.net/U7QqB/3/

JS

JS

jQuery(document).ready(function() {
  $('.click').hover(function(){
    var html = $(this).find('.text').html();   
    $('body').append('<div id="object"/>').html(html).css({'top':'200px','left':'300px','z-index':'10'});
  });
});

css

css

.click{position:realavite;top:100px;left:300px;}
.text{display:none;}
.object{position:absolute;}

html

html

<body>
<h1>A hover append div text</h1>
<div class="click">
    <img src="http://nt3.ggpht.com/news/tbn/U7Q-7enFr00rUM/1.jpg" />
    <div class="text">text</div>
</div>
</body>

回答by Frédéric Hamidi

That's because append()returns the originaljQuery object (the one containing the <body>element), not a new one containing the appended content.

这是因为append()返回原始jQuery 对象(包含<body>元素的对象),而不是包含附加内容的新对象。

You can use appendTo()instead:

您可以使用appendTo()代替:

$('<div id="object">').appendTo('body').html(html).css({
    'top': '200px',
    'left': '300px',
    'z-index': '10'
});

回答by thecodeparadox

$('<div/>',{
  id: 'object'
}).appendTo('body')
  .html(html)
  .css({
     'top': '200px',
     'left': '300px',
     'z-index': '10'
});