2010-08-25 36 views
1

我需要確定哪個元素在我的標記中最先出現,如inputselect。例如確定HTML/DOM中哪個元素最先出現?

<body> 
    <input type="text" /> 
    <select><option>Test</option></select> 
<body> 

在這種情況下,input至上在DOM而

<body> 
    <select><option>Test</option></select> 
    <input type="text" /> 
<body> 
在這種情況下

select至上。任何方式來使用jQuery做到這一點?謝謝

編輯:只是爲了澄清,我不想要的第一個元素,我只想知道,如果之間的輸入和選擇元素,首先來。在selectinput元素之前可能還有其他元素。

回答

3

使用index。 如果$('select:first').index() < $('input:first').index()那麼select是第一

在這裏看到一個樣本:http://jsfiddle.net/ZLmMB/

+0

謝謝,這正是我正在尋找的 – axsuul 2010-08-25 23:58:20

+1

只要第一個'select'和'input'是兄弟姐妹,這就會工作。如果不是,'.index()'不是一個可靠的指標。 – user113716 2010-08-25 23:58:34

+0

@ user113716確實,看到這個例子:http://jsfiddle.net/ZLmMB/2/ – Shawn 2012-04-18 19:01:43

2

如果你想在<body>非常第一個元素,你可以使用:first-child這樣的:

$("body > :first-child") 

例如你在第一個例子:

alert($("body > :first-child")[0].nodeName);​ //alerts "INPUT" 

You can give it a try here


或獲得第一輸入類型,你可以這樣做:

$(":input:first") 

例如:

alert($(":input:first")[0].nodeName);​ //alerts "INPUT" 

You can try that version here

+0

我不想要第一個元素,我想知道是否在輸入和select元素之間,哪個先到達 – axsuul 2010-08-25 23:46:24

+0

@Axsuul - 已更新爲只查看輸入類型元素:) – 2010-08-25 23:47:37

+0

@Gert - 這會找到*任何*任何級別的第一個孩子,所以它會選擇很多元素:) – 2010-08-25 23:53:57

3

如果你只是想知道哪個是第一位在整個文檔中,你可以這樣做:

試試看:http://jsfiddle.net/85zUZ/更改順序,然後點擊頂部的運行。

var theFirst = $('input,select').first()[0].tagName; 

alert(theFirst); 

jQuery的返回它們出現在DOM順序元素,所以.first()會抓住出現的順序的第一個。

相關問題