乐闻世界logo
搜索文章和话题

Reload an iframe with jQuery

1个答案

1

You can reload an iframe using jQuery by selecting the iframe element and modifying its src attribute. Here's an example code snippet:

javascript
$('#myIframe').attr('src', function(i, val) { return val; });

This code uses jQuery's .attr() method to retrieve the current src attribute value and immediately reassign it to the same value, triggering a reload of the currently loaded page.

Alternatively, if you want to reload the iframe to a new page, you can directly set a new URL:

javascript
$('#myIframe').attr('src', 'http://your.new.url.here/');

To avoid caching issues, especially when reloading the same URL, append a timestamp or random parameter to the URL:

javascript
$('#myIframe').attr('src', function() { var currentTime = new Date().getTime(); return $(this).data('src') + '?timestamp=' + currentTime; });

In this example, we use .data('src') to retrieve the original URL of the iframe (you should store this URL in the data-src attribute in your HTML). We then append a query parameter timestamp with the current time as its value. This ensures the URL is unique for each request, forcing the browser to reload resources instead of fetching them from the cache.

2024年6月29日 12:07 回复

你的答案