当我点击向上或向下按钮时,我只想让边框上下移动。
$(document).ready(function() {
$("#up").click(function() {
$("#up").prev().css("border", "2px solid blue");
});
});
$(document).ready(function() {
$("#down").click(function() {
$("p").next().css("border", "2px solid blue");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four">paragraph 4</p>
<button id="up">Up</button>
<button id="down">Down</button>
&#13;
如何使用jQuery实现这一目标?
答案 0 :(得分:2)
我就是这样做的(代码注释):
var ps = $('p'), // cache the paragraphs
currentIndex = 3; // starting at paragraph 4
$("#up").click(function() {
currentIndex -= 1; // decrement index
if (currentIndex < 0) {
currentIndex = ps.length - 1; // set back to bottom item
}
ps.removeClass('border');
ps.eq(currentIndex).addClass('border')
});
$("#down").click(function() {
currentIndex += 1; // increment index
if (currentIndex == ps.length) {
currentIndex = 0; // set back to top item
}
ps.removeClass('border');
ps.eq(currentIndex).addClass('border')
});
&#13;
.border {
border:2px solid blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four" class="border">paragraph 4</p>
<button id="up">Up</button>
<button id="down">Down</button>
&#13;
答案 1 :(得分:1)
您可以尝试这样的事情:
$(document).ready(function() {
$("#up").click(function() {
if ($("p.with-border").prev("p").length > 0) { // is there prev paragraph?
$("p.with-border").prev("p").addClass("with-border");
$("p.with-border").last().removeClass("with-border");
}
});
$("#down").click(function() {
if ($("p.with-border").next("p").length > 0) { // is there next paragraph?
$("p.with-border").next("p").addClass("with-border");
$("p.with-border").first().removeClass("with-border");
}
});
});
.with-border {
border: 2px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four" class="with-border">paragraph 4</p>
<button id="up">Up</button>
<button id="down">Down</button>