Drupal 7+jQuery求助:点击按钮无法展开对应隐藏内容
Hey there, let's figure out why your find() and closest() aren't working, and fix that toggle functionality for your Drupal 7 content!
First off, the issue almost certainly boils down to DOM structure and selector logic. find() only looks for child elements of the current element, while closest() traverses upward through parent elements. If your .hidden body content is a sibling to .featured-summary (which is super common for Drupal content blocks—summary first, then hidden body), neither method will locate it.
Let's assume your Drupal content block structure looks something like this (you can verify with browser dev tools by pressing F12):
<div class="node"> <!-- Drupal's default content node container class --> <div class="featured-summary"> Your summary text here... <button class="continue btn btn-success">Continue...</button> </div> <div class="hidden"> Your default-hidden body content here... </div> </div>
For this structure, we'll adjust the jQuery logic to use event delegation (since your buttons are dynamically added, direct click bindings won't work) and target elements correctly:
// First, append the button to each summary $('.featured-summary').append('<button class="continue btn btn-success">Continue...</button>'); // Use event delegation to bind the click event to a static parent (like document, or a closer container) $(document).on('click', '.continue', function() { // 1. Get the summary container that holds the clicked button const $summary = $(this).closest('.featured-summary'); // 2. Find the sibling .hidden body element const $body = $summary.siblings('.hidden'); // 3. Toggle visibility: show the body, hide the summary $body.slideDown(); // Use slideDown for smooth animation, or show() for instant display $summary.slideUp(); });
If your .hidden element lives inside the same parent container but isn't a direct sibling, you can target it this way instead:
$(document).on('click', '.continue', function() { // First, locate the outermost content node container (e.g., Drupal's .node class) const $contentNode = $(this).closest('.node'); // Then find the summary and body within that container const $summary = $contentNode.find('.featured-summary'); const $body = $contentNode.find('.hidden'); $body.show(); $summary.hide(); });
Why your original methods failed:
$('.featured-summary').find('.hidden'): This searches only for child elements of.featured-summary, but your body content is a sibling or part of another branch in the DOM, so it can't be found.$(this).closest('.hidden'): This traverses upward through parent elements of the button, but.hiddenisn't an ancestor of the button, so no match is made.
Just double-check your actual DOM structure with dev tools to confirm the relationship between .featured-summary and .hidden, then tweak the selectors if needed—you'll have that toggle working in no time!
内容的提问来源于stack exchange,提问作者Nick0989

