使用jQuery的publish调用subscribe函数时event.activeElement.id为空求助
event.currentTarget.activeElement.id is Empty When Using jQuery Publish/Subscribe? Hey there, let's break down why you're seeing an empty ID here and how to fix it.
The Root Cause
When you manually trigger an event using $.publish(), this isn't tied to any user-initiated DOM interaction (like clicking a dropdown or typing in an input). The activeElement property refers to the DOM element that currently has focus on the page.
In your case, when you call $.publish() inside $(document).ready(), the page hasn't had any user interactions yet—so the active element is usually the <body> or <html> tag (which don't have an id attribute set), hence the empty value.
Fixes You Can Try
1. Pass the Target Element's ID Directly in the Publish Payload
This is the cleanest and most reliable approach. Instead of relying on the event object to get the ID, just send it as part of the data when you publish the event:
// Your existing subscribe handler works as-is $.subscribe('onCmbNomineeSalutationComplete', function(event, data) { onCmbNomineeSalutationChange(data, 'complete', event); }); // Modify the publish call to include the element ID $(document).ready(function() { // Replace #cmbNomineeSalutation with your actual dropdown selector const targetElement = $('#cmbNomineeSalutation'); $.publish('onCmbNomineeSalutationComplete', { elementId: targetElement.attr('id'), // Add any other relevant data here if needed }); }); // Update your handler to use the passed ID function onCmbNomineeSalutationChange(data, status, event) { const elementId = data.elementId; // Your logic here using elementId instead of event.currentTarget.activeElement.id }
2. Manually Set Focus on the Target Element Before Publishing (Less Ideal)
If you really need to use activeElement, you can force the target element to gain focus before triggering the event. Keep in mind this might have side effects like scrolling the element into view or interrupting user focus later:
$(document).ready(function() { const targetElement = $('#cmbNomineeSalutation'); targetElement.focus(); // Force focus on the element first $.publish('onCmbNomineeSalutationComplete'); });
3. Fetch the Element Directly in Your Handler
If the target element is always the same, you can skip passing the ID altogether and just select it directly in your handler function:
function onCmbNomineeSalutationChange(data, status, event) { const targetElement = $('#cmbNomineeSalutation'); const elementId = targetElement.attr('id'); // Your logic here }
Key Takeaway
Manual event triggers (like publish) don't carry the same context as user-initiated events. Always prefer passing explicit data with your published events instead of relying on DOM focus state—it's more predictable and avoids edge cases like empty IDs.
内容的提问来源于stack exchange,提问作者aniket

