0

让我们估计我们有如下排列的元素:

<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];
}
4

2 回答 2

2

parentNode要得到你想要的,你可以div使用span. 然后你可以使用previousSibling遍历 DOM 并使用找到你想要的输入。childNodes firstChild

我很快就破解了:

var span = document.getElementsByClassName('button')[4], // one of the "button" spans
    div = span.parentNode, // get the span's parent div
    ele,  // variable to hold the element we are looking for
    temp; // temp var for the loop

while ((div = div.previousSibling) !== null) {  // Loop through all the previous divs
    temp = div.firstChild;  // get the div's children
    if (temp && temp.className === 'elementToGet') { // does it's 1st child have the class?
        ele = temp;  // we found it!
        break;
    }
}
alert(ele.value);​

演示:http: //jsfiddle.net/zH4SU/1/

于 2012-09-18T16:27:57.467 回答
1

如果您使用的是 JQuery,您可以使用.closest(),它会向上遍历 DOM 树

于 2012-09-18T16:13:06.673 回答