使用jQuery修改并加载iframe的src属性
Hey Sergio! Totally get being a jQuery and web design newbie—this stuff can feel overwhelming at first, but this task is way simpler than you might think. Let's build a minimal, easy-to-understand example that does exactly what you need:
Step 1: The HTML Structure
First, set up your iframe and buttons. We'll use a data attribute on each button to store the URL of the video it should load—this keeps your code clean and avoids repeating logic for each button.
<!-- Your iframe where videos will play --> <iframe id="videoFrame" width="640" height="360" src="" frameborder="0" allowfullscreen></iframe> <!-- Your 12 video buttons --> <button class="video-btn" data-video-url="https://your-stream-site.com/video1">Video 1</button> <button class="video-btn" data-video-url="https://your-stream-site.com/video2">Video 2</button> <button class="video-btn" data-video-url="https://your-stream-site.com/video3">Video 3</button> <!-- Add the other 9 buttons here, each with their own unique data-video-url -->
Step 2: The jQuery Code
Next, we'll write a short jQuery script that listens for button clicks, grabs the video URL from the button's data attribute, and updates the iframe's source.
First, make sure you've included jQuery in your page (add this right before your closing </body> tag if you haven't already):
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
Then add this script right after it:
$(document).ready(function() { // Listen for clicks on any button with the "video-btn" class $('.video-btn').click(function(e) { // Prevent any default browser behavior (good practice even if not strictly needed here) e.preventDefault(); // Grab the video URL stored in the clicked button's data attribute const videoUrl = $(this).data('video-url'); // Update the iframe's source to load the new video instantly $('#videoFrame').attr('src', videoUrl); }); });
Quick Breakdown For Newbies
Let's make sure you understand every part:
$(document).ready(function() { ... }): Ensures our code only runs after the page's HTML has fully loaded (so jQuery can find the buttons and iframe).$('.video-btn').click(function(e) { ... }): Attaches a click event to every button with thevideo-btnclass—no need to write code for each individual button!$(this).data('video-url'):thisrefers to the button you just clicked. We're pulling the unique video URL stored in itsdata-video-urlattribute.$('#videoFrame').attr('src', videoUrl): Updates the iframe'ssrcattribute with the new video URL. This tells the iframe to load the new video immediately, no page refresh required.
This setup is super scalable too—adding more buttons later just means adding another <button> with a new data-video-url, no extra code needed!
内容的提问来源于stack exchange,提问作者Sergio santa

