I have a simple div created using jQuery ....
var split = document.createElement('div');
split.className ="item split";
$(split).html('<strong>SPLITTER</strong>');
I want to use the same variable in several simple functions. However, it seems that whenever I transfer a variable from a function, I can only create a div once. Then all other instances cannot insert the div.
Check out the snippet, it will probably help explain better.
$('#divide_btn').on('click', function() {
var split = document.createElement('div');
split.className = "item split";
$(split).html('<strong>SPLITTER</strong>');
$(split).hide(function() {
}).insertAfter('.moved:last').slideDown(300);
});
var split2 = document.createElement('div');
split2.className = "item split";
$(split2).html('<strong>SPLITTER 2</strong>');
$('#divide_btn2').on('click', function() {
$(split2).hide(function() {
}).insertAfter('.moved:last').slideDown(300);
});
body {
padding: 0 20px;
margin: 0;
}
span {
display: inline-block;
margin: 5px;
background: #aaa;
color: #eee;
padding: 5px 10px;
}
.item,
.moved,
.split {
padding: 5px 10px;
margin: 3px;
background: #eee;
}
.moved {
background: #fee;
}
.split {
background: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span id="divide_btn">click for internal variable</span><span id="divide_btn2">click for external variable</span>
</p>
<div class="main">
<div class="item">item</div>
<div class="item moved">item</div>
<div class="item">item</div>
<div class="item">item</div>
</div>
Run codeHide resultNote the difference: for the “inner” button, the div is created in the click function, and every time I click on a new div, it is created (as expected).
For an “external” button, a variable is created outside the click function and only one div can be created.
div , , ?
"" .. div , .
( , div ... .)