如何按用户登录状态控制CMS加载的Account标签页显隐?
Hey Sarah, let's break down why your jQuery selectors aren't working and get this sorted out quickly!
The Core Issues
Looking at your HTML output and code, there are two main reasons your selectors failed:
- Mismatched Title Attribute: Your HTML shows the
titleattribute is" Account"(note the leading space), but your selectors are looking for[title="Account"]without that space—so they can't match the element. - DOM Timing: If your
Check()function runs before the CMS finishes loading the tab into the DOM, the selectors won't find any elements to hide/show.
Step-by-Step Solution
1. Fix the Selector to Handle Spaces
Instead of exact matching, use a more flexible approach to account for leading/trailing spaces in the title attribute. Here are two reliable options:
Option A: Use a Contains Selector (Simple)
This matches any a tag whose title includes the word "Account", regardless of surrounding spaces:
function Check() { JApi.Services.CheckLoginAccount(function(account) { // Target the parent <li> of the Account tab link const accountTab = $('#menu li a[title*="Account"]').closest('li'); if (account == null) { accountTab.hide(); // Hide when not logged in } else { accountTab.show(); // Show when logged in } }); }
Option B: Use filter() for Exact Trimmed Match (Precise)
If you want to avoid matching other tabs that might include "Account" in their title, use filter() to trim the title value first:
function Check() { JApi.Services.CheckLoginAccount(function(account) { const accountTab = $('#menu li a').filter(function() { // Trim whitespace from the title and check for exact match return $(this).attr('title').trim() === 'Account'; }).closest('li'); accountTab.toggle(account != null); // Toggle visibility based on login status }); }
2. Ensure Timing is Correct
Make sure your Check() function runs after the CMS has loaded the tab into the DOM. The easiest way is to wrap it in $(document).ready() to wait for the full DOM to render:
$(document).ready(function() { // Run login check once the page is fully loaded Check(); });
If your CMS loads tabs asynchronously (e.g., via an API call), you'll need to call Check() in the CMS's load-completion callback instead.
3. Test the Selector First
To verify your selector works, open your browser's developer tools (F12), go to the Console tab, and run:
$('#menu li a[title*="Account"]').closest('li')
If it returns the correct <li> element, your selector is good—you just need to make sure the timing is right.
Why Your Original Selectors Failed
- Your first selector
$('#menu a[title="Account"]').closest('ul').hide()was targeting the wrong parent (the submenu<ul>instead of the main tab<li>), and the title match was incorrect. - The second selector
$(document).find('#menu li a[title = "Account"]').parent().hide()failed because of the leading space in thetitleattribute—exact string matching doesn't ignore whitespace.
内容的提问来源于stack exchange,提问作者Sarah

