我一直在学习自己编写代码,而且我的Javascript知识非常基础......当我尝试遍历列表时,我遇到了一个问题,我想要包装其索引与列出并摆脱其他人.....当然不是我想要的,这就是我所拥有的:
<div id='wrapper'>
<ul id='list'>
<span id='next'>Next</span>
<li>Cat</li>
<li>Dog</li>
<li>Eagle</li>
<li>Fox</li>
<li>Mouse</li>
<span id='prev'>Prev</span>
<div id='ci'></div>
</ul>
var current_index = 0;
var uli = $("#list li");
function cycle(){
var start = uli.eq(current_index);
$("#ci").html(current_index);
//alert(uli.index(start))
var pic = uli.index(start);
if(start.parent().is('#this')){
start.unwrap();
}else if(current_index == pic){
start.wrap("<div id='this'></div>");
}
}
$('#next').click(function(){
current_index += 1;
if(current_index > uli.length - 1){
current_index = 0;
}
cycle();
});
$('#prev').click(function(){
current_index -= 1;
if(current_index < 0){
current_index = uli.length -1;
}
cycle();
});
我希望我已经解释过自己并感谢您的时间我真的很感激!!!
答案 0 :(得分:0)
你需要包装li
的内部内容并打开#this
的内容
function cycle() {
$("#ci").html(current_index);
$('#this').contents().unwrap();
uli.eq(current_index).wrapInner('<div id="this"></div>');
}
var current_index = -1;
var uli = $("#list li");
function cycle() {
$("#ci").html(current_index);
$('#this').contents().unwrap();
uli.eq(current_index).wrapInner('<div id="this"></div>');
}
$('#next').click(function() {
current_index++;
if (current_index > uli.length - 1) {
current_index = 0;
}
cycle();
});
$('#prev').click(function() {
current_index--;
if (current_index < 0) {
current_index = uli.length - 1;
}
cycle();
});
#this {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='wrapper'>
<!-- should be outside of the ul as span can't be a direct child of ul -->
<span id='next'>Next</span>
<ul id='list'>
<li>Cat</li>
<li>Dog</li>
<li>Eagle</li>
<li>Fox</li>
<li>Mouse</li>
</ul>
<!-- should be outside of the ul as span/div can't be a direct child of ul -->
<span id='prev'>Prev</span>
<div id='ci'></div>
</div>
答案 1 :(得分:0)
在你的代码中:
$('#prev').click(function(){
current_index -= 1;
if(current_index < 0){
current_index = uli.length -1;
}
// delete all other highlighted
$('.highlight').removeClass('highlight');
// make this highlighted
$(this).addClass('highlight');
cycle();
});
并以css为例:
.highlight {
border: 1px solid green;
}