jQuery: Loading iframe on click - how to write man

2019-09-06 02:33发布

问题:

looking for some feedback / advice from advanced web devs on how to actually write manageable code for this scenario.

Scenario

We have various links on the site in containers. Upon clicking one of these, we use jQuery to create an iframe and load a page in it.

HTML part: (starting after body)

    <a id="slot1" href="#0">Text</a>
    <a id="slot2" href="#0">Text</a>
    <a id="slot3" href="#0">Text</a>
    <a id="slot4" href="#0">Text</a>

    <!-- iframe content will be displayed within this div -->
    <div id="content">
    </div>

jQuery:

    <script>
    $("#slot1").click(function(){$("#content").html('<iframe src="http://www.google.de/">');});
    $("#slot2").click(function(){$("#content").html('<iframe src="http://www.google.com/">');});
    $("#slot3").click(function(){$("#content").html('<iframe src="http://www.google.co.uk/">');});
    $("#slot4").click(function(){$("#content").html('<iframe src="http://www.google.ru/">');});
    </script>

Now this gets tedious and redundant if the list grows (think of #slot57 !). How to write it more flexible and elegant?

So far I thought of targeting all slot IDs $('[id^="slot"]') and slicing the index(4) in order to get the actual clicked number. But then how to load the right iframe content!?

I'm stuck. Any thoughts / advice?

回答1:

if you are able to do some markup modification then you can try to do this in the markup:

<a id="slot1" href="#google.de/">Text</a>
<a id="slot2" href="#google.com/">Text</a>
<a id="slot3" href="#google.co.uk/">Text</a>
<a id="slot4" href="#google.ru/">Text</a>

then you can use this jQuery code:

$('a[id^="slot"]').on('click', function(e){
    e.preventDefault(); // stops the jump of anchor
    $("#content").html('<iframe src="http://www.'+ $(this).attr('href').slice(1) +'">');
});

or a better one if you are using html5 then use data-* attribute to serve the url:

<a id="slot1" href="#0" data-url="http://www.google.de/">Text</a>
<a id="slot2" href="#0" data-url="http://www.google.com/">Text</a>
<a id="slot3" href="#0" data-url="http://www.google.co.uk/">Text</a>
<a id="slot4" href="#0" data-url="http://www.google.ru/">Text</a>

then you can use this jQuery code:

$('a[id^="slot"]').on('click', function(e){
    e.preventDefault(); // stops the jump of anchor
    $("#content").html('<iframe src="http://www.'+ $(this).data('url') +'">');
});

Fiddle



回答2:

You Can Try This

HTML

<a class='slots' href="http://www.google.de/">Text1</a>
    <a class='slots'href="http://www.google.com/">Text2</a>
    <a class='slots'  href="http://www.google.uk/">Text3</a>
    <a  class='slots' href="http://www.google.ru/">Text4</a>

    <!-- iframe content will be displayed within this div -->
    <div id="content">
    </div>

JS

  $('a').click(function(e){
   $("#content").html('<iframe src='+$(this).attr('href')+'>');
    e.preventDefault();
});

DEMO HERE



标签: jquery iframe