2017-04-11 56 views
1

如何使這一個li元素將是第一個,因爲用戶在下一頁單擊(www.url.com/demo/#collapse1) - 應該是第一個或(www.url.com/demo/#collapse5) - 是第一個嗎?當你在同一頁面時,其他元素將留在他們的位置。 www.url.com/demo只有一個列表元素首先在頁面加載

$('li').click(function() { 
 
    $(this).prependTo($(this).parent()); 
 
});
body { 
 
    font-family: verdana; 
 
    font-size: 12px; 
 
} 
 

 
a { 
 
    text-decoration: none; 
 
    color: #000; 
 
    display: block; 
 
    width: 100%; 
 
    padding: 8px 0; 
 
    text-indent: 10px; 
 
} 
 

 
a:hover { 
 
    text-decoration: underline; 
 
} 
 

 
ul { 
 
    list-style: none; 
 
} 
 

 
ul li { 
 
    background: #eee; 
 
    margin-bottom: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li><a href="#one">01</a></li> 
 
    <li><a href="#two">02</a></li> 
 
    <li><a href="#three">03</a></li> 
 
    <li><a href="#four">04</a></li> 
 
    <li><a href="#">05</a></li> 
 
</ul>

+3

不清楚自己想要達到的目標,你能解釋一下多一點 –

+0

例如:你在Facebook和看到www.url.com /#東西鏈接。 你點擊了它。該元素是頁面上的最後一個,但他首先是因爲你點擊了該鏈接,但其他人ements留在他們的地方。 – Mantas

+0

所以在你的例子中,如果我點擊'3',它就會上升(現在訂單是'3 - 1 - 2 - 4 - 5'),然後如果你點擊4,那麼訂單就是('4-3 - 1 - 2 - 5'),但你真的想要:'(4 - 1 - 2 - 3 - 5)'? –

回答

3

我敢肯定你正在尋找一種方式,第一個元素和點擊元素之間切換。這是通過使用.detach來實現這一點的一種方法。首先,我們抓住.siblings,然後我們通過.eq從列表中獲取第一個元素。接下來,我們將我們點擊的元素添加到父元素中,只在將元素first添加到我們的當前元素之後,纔將其分開,基本上, 。交換兩個元素

$('li').click(function() { 
 
    first = $(this).siblings().eq(0).detach() 
 
    $(this).parent().prepend($(this).after(first).detach()); 
 
}); 
 

 
if (window.location.hash != "") { 
 
\t $('li').eq(Number(window.location.hash.slice(1))-1).click(); 
 
}
body { 
 
    font-family: verdana; 
 
    font-size: 12px; 
 
} 
 

 
a { 
 
    text-decoration: none; 
 
    color: #000; 
 
    display: block; 
 
    width: 100%; 
 
    padding: 8px 0; 
 
    text-indent: 10px; 
 
} 
 

 
a:hover { 
 
    text-decoration: underline; 
 
} 
 

 
ul { 
 
    list-style: none; 
 
} 
 

 
ul li { 
 
    background: #eee; 
 
    margin-bottom: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li><a href="#1">01</a></li> 
 
    <li><a href="#2">02</a></li> 
 
    <li><a href="#3">03</a></li> 
 
    <li><a href="#4">04</a></li> 
 
    <li><a href="#5">05</a></li> 
 
</ul>

+0

太棒了。你能解釋一下你的邏輯嗎? –

+0

@TamilSelvanC我用我解釋過的邏輯更新了我的答案。 – Neil

+0

但我怎樣才能做到這一點與鏈接?例如:如果用戶轉到「url /#two」,那麼順序是:2 - 1 - 3 - 4 - 5,然後用戶點擊3,url爲:url /#3,順序爲:3 - 1 - 2 - 4 - 5. – Mantas

相關問題