Load IFRAME onClick

2019-08-30 03:23发布

问题:

I have IFRAMEs loading onClick.

The problem with the following script is that always loads the content of the first iframe, while I'm expecting to load JUST the right iframe when I click on the relative link.

$('.toggle-next-div').click(function(){
var iframe = $("#myiFrame");
iframe.attr("src", iframe.data("src")); 
});

HTML

<a href="#" class="toggle-next-div">Map</a>// iframe (1)
<iframe id="myiFrame" data-src="my-url" src="about:blank"></iframe   
<a href="#" class="toggle-next-div">Map</a>// iframe (2)
<iframe id="myiFrame" data-src="my-url" src="about:blank"></iframe>
<a href="#" class="toggle-next-div">Map</a>// iframe (3)
<iframe id="myiFrame" data-src="my-url" src="about:blank"></iframe   
<a href="#" class="toggle-next-div">Map</a>// iframe (and so on...)
...

How to load just the iframe for the relative link?

回答1:

Don't use the same ID. You can use a class:

<a href="#" class="toggle-next-div">Map</a>// iframe (1)
<iframe class="myiFrame" data-src="my-url" src="about:blank"></iframe>  
<a href="#" class="toggle-next-div">Map</a>// iframe (2)
<iframe class="myiFrame" data-src="my-url" src="about:blank"></iframe>


$('.toggle-next-div').click(function(e) {
  e.preventDefault();
  var iframe = $(this).next();
  iframe.attr("src", iframe.attr("data-src")); 
});