让我们估计我们有如下排列的元素:
<div><input class="elementToGet" value="1"></div> // st elementToGet
<div><span class"button">get prev elementToGet</span></div> // Nr1
<div><span class"button">get prev elementToGet</span></div> // Nr2
<div><span class"button">get prev elementToGet</span></div> // Nr3
<div><input class="elementToGet" value="2"></div> // nd elementToGet
<div><span class"button">get prev elementToGet</span></div> // Nr4
<div><span class"button">get prev elementToGet</span></div> // Nr5
<div><span class"button">get prev elementToGet</span></div> // Nr6
如何获得elementToGet
每个跨度的前一个?
例如,从 4 开始编号的元素将获得第二个elementToGet
.
无需框架的 Javascript。
function getPrev(className) {
var items = [], myPosts = document.getElementsByClassName(className);
for (var i = 0; i < myPosts.length; i++) {
// I have no ideas what to do next
items.push(myPosts[i]);
}
return items[0];
}