jQuery:点击加载iframe - 如何编写可管理的代码? [英] jQuery: Loading iframe on click - how to write manageable code?

查看:130
本文介绍了jQuery:点击加载iframe - 如何编写可管理的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找高级网络开发人员关于如何为此方案实际编写可管理代码的一些反馈/建议。

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

场景

我们在网站上有各种容器链接。单击其中一个后,我们使用jQuery创建iframe并在其中加载页面。

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部分:(从正文开始)

    <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>

如果列表增长,这会变得冗长乏味(想想#slot57!)。如何写它更灵活和优雅?

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

到目前为止,我想到了所有插槽ID $('[id ^ =slot]')和切片索引(4)以获得实际点击的数字。但接下来如何加载正确的iframe内容!?

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?

推荐答案

如果你能做一些标记修改,那么你可以尝试在标记中执行此操作:

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>

然后你可以使用这个jQuery代码:

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) +'">');
});






或者如果你使用的话更好> html5 然后使用数据 - * 属性来提供网址:


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>

然后你可以使用这个jQuery代码:

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') +'">');
});

这篇关于jQuery:点击加载iframe - 如何编写可管理的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆