基于状态控制表格行链接可用性的jQuery实现问询
Got it, let's adjust your jQuery code to only allow clicks on rows with the Ledig status, and disable redirects for Udlejet rows. Here's a clean implementation using if/else logic, plus fixes for a small selector issue in your original code:
Step 1: Fix & Combine Your Code
First, note your original click handler had a missing dot in the class selector (table-link should be .table-link). We'll also integrate the conditional check alongside your existing code for adding status classes to rows:
jQuery(document).ready(function( $ ){ // Add status classes to table rows (keep your existing code, plus trim() to avoid whitespace issues) $('.table-2 tr').addClass(function() { return $(this).find('.status').text().trim(); }); // Conditional click handler for table rows $('.table-link').click(function(e) { const $row = $(this); // Check if the row has the "Ledig" status class if ($row.hasClass('Ledig')) { // Allow redirect to the data-href URL window.document.location = $row.data("href"); } else { // Prevent the default click action (disables redirect) e.preventDefault(); // Optional: Add visual feedback for disabled rows (uncomment if needed) // alert("Denne enhed er udlejet og kan ikke vælses."); } }); });
How This Works
- Selector Fix: The
.table-linkclass selector now correctly targets rows with that class (your original code missed the leading dot). - Whitespace Handling:
trim()ensures we don't accidentally match text with extra spaces (like line breaks or indentation in the HTML). - Conditional Check: We use
hasClass('Ledig')to check the status class we already added to the row—this is efficient because we're reusing the existing class instead of re-querying the status cell. - Disable Redirect: For non-Ledig rows,
e.preventDefault()stops the default click behavior, so the browser won't navigate to thedata-hrefURL.
Alternative: Check Status Text Directly
If you prefer not to rely on the row classes, you can check the status cell's text directly in the click handler:
jQuery(document).ready(function( $ ){ $('.table-link').click(function(e) { const status = $(this).find('.status').text().trim(); if (status === 'Ledig') { window.document.location = $(this).data("href"); } else { e.preventDefault(); } }); // Keep your addClass code if you need it for styling $('.table-2 tr').addClass(function() { return $(this).find('.status').text().trim(); }); });
This approach is more self-contained, but slightly less efficient since it queries the status cell every time a row is clicked (vs. using the pre-added class).
内容的提问来源于stack exchange,提问作者S. Gski

