[英]What information about a DOM element would allow JavaScript to identify it (somewhat) uniquely? (e.g. when it doesn't have `id`)
[英]Identify a DOM element between requests if DOM element doesn't have an id attribute?
我寫了一個快速而骯臟的解決方案,使用localStorage
(實際上是在store.js shim的幫助下)存儲(並激活)頁面請求上最后選擇的Bootstrap 3導航選項卡窗格。 看來工作正常,是的,我不太擅長JavaScript。
無論如何,腳本都會存儲根據window.location.href
和nav tabs id
屬性計算的密鑰:
<!-- Nav tabs -->
<ul id="nav-tab-settings" class="nav nav-tabs nav-remember">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#messages" data-toggle="tab">Messages</a></li>
<li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home"><h2>Home</h2></div>
<div class="tab-pane" id="profile"><h2>Profile</h2></div>
<div class="tab-pane" id="messages"><h2>Messages</h2></div>
<div class="tab-pane" id="settings"><h2>Settings</h2></div>
</div>
問題 :導航選項卡的id
屬性在Bootstrap 3中不是必需的。能否在不強制設置id
屬性的情況下使腳本工作? 有沒有一種方法可以識別沒有id
(可能是其位置)的DOM元素? 如果同一頁面在請求之間返回稍微修改的DOM怎么辦?
如果有問題,這里是腳本navs-remember.js
:
(function ($, store) {
// Storage not available
if (!store.enabled) {
return;
}
$(function () {
var tabsSelector = '.nav.nav-tabs.nav-remember[id]',
toggleSelector = 'a[data-toggle="tab"][href]';
// Identify each nav tabs by current location and its id
var computeStorageKey = function (navId) {
return window.location.href + '#' + navId;
};
// Restore last selected tab
$(tabsSelector).each(function () {
var nav = $(this),
navId = nav.attr('id'),
storedActiveHref = store.get(computeStorageKey(navId)),
lastActiveToggle = null;
if (!navId.length || (undefined === storedActiveHref)) {
return;
}
// Get the toggle itself
lastActiveToggle = nav.find('a[href="' + storedActiveHref + '"]')
.first();
// Show the tab
if (lastActiveToggle.length) {
lastActiveToggle.tab('show');
}
});
$(tabsSelector + ' ' + toggleSelector).click(function () {
var toggle = $(this),
toggleHref = toggle.attr('href'),
nav = toggle.closest(tabsSelector),
navId = nav.attr('id');
// Store toggle href attribute value
if (toggleHref.length && nav.length && navId.length) {
store.set(computeStorageKey(navId), toggleHref);
}
});
});
}(jQuery, store));
您可以使用jQuery.eq(index)
將其按位置放置在jquery結果中,因此要獲取“ home”標簽,您需要查找$("tabselector li").eq(0)
請注意,它是基於0的。
文檔: https : //api.jquery.com/eq/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.