简体   繁体   中英

Add CSS Class after HTML div using JQuery

I have this HTML

            <div class="portItem"></div>
            <div class="portItem"></div>
            <div class="portItem"></div>
            <div class="portItem"></div>

This CSS

 .rectangle {
   height: 250px;
   width: 100%;
   position: relative;
   display: none;
   background: #ffffff;
   box-shadow: 1px 0px 20px black;
   overflow-y: hidden;}

      Here's the CSS for portItem, although not necessary (forms 4 green blocks next to each other)

     .portItem {
       height: 180px;
       width: 250px;
       position: relative;
       display: inline-block;
       background: #D0E182;
        margin: 0 5px 5px 0;

And I'm trying to add the CSS rectangle after any of the portItems that I click on.

Here's the JQuery function I'm trying to use:

 $(document).ready(function() {
   $('.portItem').click(function() {
     addDiv($(this));
   });
 });



 function addDiv($ele) {
   var $box = $('<div />' '.rectangle');
   $box.insertAfter($ele);
 }

The problem is with the var $box statement, I can't get it to work.

Thanks in advance!

You're missing a comma, and an object.

var $box = $('<div />', {'class':'rectangle'});
// -------------------^ ^                   ^
//    added comma-----| |___________________|---and object literal syntax

The quotes around class are needed to support older browsers. You could also use className instead.

var $box = $('<div />', {className:'rectangle'});

How about this:

var $box = $('<div/>').addClass('rectangle');

... or as simple as...

var $box = $('<div class="rectangle"/>');

Actually, I might consider preparing this item first-hand, then just cloning it. For example:

var $boxTemplate = $('<div class="rectangle">');
function addDiv($ele) {
   $boxTemplate.clone().insertAfter($ele);
}

将var $ box行更改为:

var $box = $('<div class="rectangle" />');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM