Automatically order injected elements
I want to be able to inject elements to a container – say, list items to a list – individually and at any given time, but only once.
I'm aware that I can inject into specific positions using .append()
, .wrap()
and other DOM insertion techniques. As suggested here.
But what to do if I don't know the order in which the user chooses to inject them (if at all) ? Sure, I can create a whole self-made method that grants the right order and such … my actual question however is, if there is an HTML attribute which defines a native or semantic order. Similar to how the role
attribute provides semantics to an element.
I'm also aware that I can use the CSS construct display: table, table-footer-group, etc.
– but that limits me to just three "groups". I probably need more.
I did it like so, setting it up with hidden placeholders. It works alright because these list items need to have IDs, anyway. But I personally don't think this is the most elegant solution.
I've added some extra gimmicks in order to emphasize that each button is supposed to behave differently. There's more going on than just the insertion of these list items.
function reset()
{
$('ul').html(
'<li class="hidden">reserved slot #0</li>'
+'<li class="hidden">reserved slot #1</li>'
+'<li class="hidden">reserved slot #2</li>'
+'<li class="hidden">reserved slot #3</li>'
);
$('body').css({
fontStyle: 'normal',
backgroundColor: ''
});
$('#text').text('');
}
$(document).ready(function(){
reset();
$('input').click(function(){
if (this.id == 'butt_reset') {
reset();
}
else {
var n = $(this).data('reference');
var $el = $('li').eq(n);
switch(n) {
case 0:
if (!document.querySelector('#li0')) {
$el.replaceWith('<li id="li0">Hansel and Gretel got lost in the forest,</li>');
$('body').css('background-color', 'blanchedalmond');
}
break;
case 1:
if (!document.querySelector('#li1')) {
$el.replaceWith('<li id="li1">It was so dark and so bitterly cold.</li>');
$('body').css('font-style', 'italic');
}
break;
case 2:
if (!document.querySelector('#li2')) {
$el.replaceWith('<li id="li2">They came to a fine little gingerbread house.</li>');
$('#text').append('lorem ipsum<br />');
}
break;
case 3:
if (!document.querySelector('#li3')) {
$el.replaceWith('<li id="li3">Who could be the lord of this little house?</li>');
$('body').css('background-color', 'indianred');
}
break;
}
}
});
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text"></div>
<ul></ul>
<input type="button" id="butt_inject0" data-reference="0" value="inject #0" />
<input type="button" id="butt_inject1" data-reference="1" value="inject #1" />
<input type="button" id="butt_inject2" data-reference="2" value="inject #2" />
<input type="button" id="butt_inject3" data-reference="3" value="inject #3" />
<input type="button" id="butt_reset" value="reset" />
链接地址: http://www.djcxy.com/p/36634.html
上一篇: 使用Java获取当前工作目录
下一篇: 自动订购注入的元素