如何在jquery中添加一个类

时间:2014-04-12 10:23:52

标签: javascript jquery html css prepend

当我点击它时,我想在盒子上添加具有相同设计的新div!但是我可以点击它,然后它就像我希望的那样出现新的div,但我想在当时添加一个不超过一个。我的意思是如果我点击一次,一个新的div应该出现,如果我再次点击1应该出现一个新的div。但是当我多次点击它会增加不止一个!为什么呢?

$(".answered_box").click(function () {
$(".answered_box").prepend('<div class="answered_box"> hej </div>');
 });

http://jsfiddle.net/jbNEC/

感谢您的帮助!

5 个答案:

答案 0 :(得分:1)

这样做:

<div id="container">
<div class="answered_box"> test </div>
</div>

和jquery:

$(document).ready(function () { 

$(".answered_box").live('click',function () {
    $('#container').append($(this).clone());
     });

});

这是Fiddle DEMO

答案 1 :(得分:1)

您可能想要使用它: -

$(this).prepend('<div class="answered_box"> hej </div>');

答案 2 :(得分:1)

$(document).ready(function () { 
    $(".answered_box").click(function () {
        // only apply on "this" and not on all members with the class.
        $(this).prepend('<div class="answered_box"> hej </div>');  
   });
});

答案 3 :(得分:0)

您的代码正在将带有类answered_box的div添加到具有类answered_box的所有div。你应该添加父div并将div添加到那里。

答案 4 :(得分:0)

使用关键字,这意味着所有者只会执行当前的div(类),并且省略其他div。

 $(document).ready(function () { 

 $(".answered_box").click(function () {
$(this).append('<div class="answered_box"> hej </div>');
  });

 });