Summernote内容填充iframe中第二个元素失败的技术求助
Hey there, let's break down why your content is loading into #intro_one but not #intro_one_mobile in the iframe—especially since you confirmed mock data works for the mobile element. Here are the most likely fixes and checks to run:
1. Double-Check Element Selector & Existence
First, make sure the target element actually exists and your selector is spot-on:
- IDs are case-sensitive! If the element’s ID is
#Intro_One_Mobile(with capital letters) instead of#intro_one_mobile, jQuery won’t find it. - Verify the element is present when your code runs by logging to the console:
If this returnsconsole.log(previewContent.find('#intro_one_mobile').length);0, the element isn’t accessible at that moment—skip to step 3 for timing fixes.
2. Confirm Element Type Matches Your Method
If #intro_one_mobile is a <textarea> or <input> instead of a <div>/<p>, using .html() won’t work. Swap it for .val() instead:
previewContent.find('#intro_one_mobile').val(intro1);
Mock data might have worked if you used .text() or .val() accidentally, so this is a quick check.
3. Fix Timing: Ensure the Element is Loaded
If the iframe or its content loads dynamically, your code might run before #intro_one_mobile exists. Try wrapping your logic in the iframe’s load event to wait for content to fully render:
$('iframe').on('load', function() { var previewContent = $(this).contents(); var intro1 = $('#intro-summernote').code(); previewContent.find('#intro_one').html(intro1); previewContent.find('#intro_one_mobile').html(intro1); });
If the mobile element is added after the iframe loads (e.g., via AJAX), use a MutationObserver to wait for it to appear:
var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { const mobileElement = previewContent.find('#intro_one_mobile'); if (mobileElement.length) { mobileElement.html($('#intro-summernote').code()); observer.disconnect(); // Stop listening once we've updated the element } }); }); // Watch the iframe's body for new elements observer.observe(previewContent[0].body, { childList: true, subtree: true });
4. Verify the previewContent Context
Make sure previewContent is correctly pointing to the iframe’s document. If it’s redefined or overwritten somewhere else in your code, it might lose access to the mobile element. Re-declare it right before use to rule this out:
var previewContent = $('iframe').contents(); // Re-fetch the iframe context var intro1 = $('#intro-summernote').code(); previewContent.find('#intro_one').html(intro1); previewContent.find('#intro_one_mobile').html(intro1);
Since mock data works, the element itself is capable of being updated—this narrows the issue to selector accuracy, timing, or method mismatch. Start with the console log check to confirm the element is accessible, then work through the other fixes.
内容的提问来源于stack exchange,提问作者Brendan Mullan

