我在使用以下代码时遇到问题,因为 li 元素从类为 center 的 div 中输出
<!doctype html><html><head>
<style>
#selectable {line-height:3em}
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white}
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; display:inline}
.center { margin: 0 auto; width: 50%; background: silver; height:500px}
</style>
<link rel="stylesheet" href="jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var arr=['33033', '04444', '00555', '333333', '4444444', '555555', '666666', '77777', '666666', '77777'];
$(document).ready(function() {
for (var i = 0; i < 10; i++) {
$("#selectable").append("<li class='ui-widget-content'>" +arr[i] + "</li>");
}
});
});
$( function() {
$( "#selectable" ).selectable({
stop: function() {
var result = $( "#select-result" ).empty();
$( ".ui-selected", this ).each(function() {
var index = $( "#selectable li" ).index( this );
result.append( " #" + ( index + 1 ) );
});
}
});
} );
</script>
</head>
<body>
<div class="center">
<ol id="selectable"></ol>
</div>
</body>
我该如何解决?
请注意,您需要在本地磁盘上安装 jquery-ui.css 才能重播效果。
最佳答案
如果选择器样式(对于 #selectable li
)更改如下,相信它会产生预期的结果:
#selectable li {
margin: 3px;
padding: 0.4em;
font-size: 1.4em;
display: inline-block;
}
要使用的代码段:
$(document).ready(function() {
var arr = ['33033', '04444', '00555', '333333', '4444444', '555555', '666666', '77777', '666666', '77777'];
for (var i = 0; i < 10; i++) {
$("#selectable").append("<li class='ui-widget-content'>" + arr[i] + "</li>");
}
});
$(function() {
$("#selectable").selectable({
stop: function() {
var result = $("#select-result").empty();
$(".ui-selected", this).each(function() {
var index = $("#selectable li").index(this);
result.append(" #" + (index + 1));
});
}
});
});
#selectable {
line-height: 3em
}
#selectable .ui-selecting {
background: #FECA40;
}
#selectable .ui-selected {
background: #F39814;
color: white
}
#selectable {
list-style-type: none;
margin: 0;
padding: 0;
width: 60%;
}
#selectable li {
margin: 3px;
padding: 0.4em;
font-size: 1.4em;
display: inline-block;
}
.center {
margin: 0 auto;
width: 50%;
background: silver;
height: 500px
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="center">
<ol id="selectable"></ol>
</div>
建议:
- 避免在
$(document).ready
中使用$(document).ready
- 我们可以使用数组长度属性 (
arr.length
),而不是在循环中使用硬编码值(10,即数组中元素的数量):
for (var i = 0; i < arr.length; i++) { $("#selectable").append("<li class='ui-widget-content'>" + arr[i] + "</li>"); }
关于javascript - 元素从 div 中出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322605/