Home >Web Front-end >JS Tutorial >How to Correctly Modify iFrame Source Using JavaScript?
When faced with the task of dynamically updating an iframe's src attribute in response to user interaction, one may encounter unexpected errors. Let's investigate a typical example where the desired functionality is to change the src attribute of an iframe labeled "calendar" upon clicking a radio button.
Here's the code in question:
<code class="html">function go(loc) { document.getElementById('calendar').src = loc; }</code>
<code class="html"><iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe></code>
<code class="html"><input name="calendarSelection" type="radio" onselect="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day</code>
However, this code fails to perform its intended action. The issue lies in a common programming error: improper use of brackets when referencing the 'calendar' iframe.
The correct syntax should be:
document.getElementById('calendar').src = loc;
Instead of the erroneous:
document.getElementById['calendar'].src = loc;
The single quotes surrounding 'calendar' in the latter example create a string, which results in a reference to a nonexistent element. By using square brackets, we are correctly referring to the iframe with the id 'calendar'.
Once this correction is made, the code should function as expected, smoothly updating the iframe's src attribute when a radio button is clicked.
The above is the detailed content of How to Correctly Modify iFrame Source Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!