jQuery:单击加载iframe-如何编写可管理的代码?
正在寻找高级web开发人员关于如何为该场景编写可管理代码的反馈/建议 场景 我们在网站上有各种容器链接。单击其中一个后,我们使用jQuery创建一个iframe并在其中加载一个页面 HTML部分:(从正文后开始)jQuery:单击加载iframe-如何编写可管理的代码?,jquery,iframe,Jquery,Iframe,正在寻找高级web开发人员关于如何为该场景编写可管理代码的反馈/建议 场景 我们在网站上有各种容器链接。单击其中一个后,我们使用jQuery创建一个iframe并在其中加载一个页面 HTML部分:(从正文后开始) jQuery: <script> $("#slot1").click(function(){$("#content").html('<iframe src="http://www.google.de/">');}); $("#slot
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>
$(“#slot1”)。单击(function(){$(“#content”).html(“”)};
$(“#slot2”)。单击(函数(){$(“#内容”).html(“”);});
$(“#slot3”)。单击(function(){$(“#content”).html(“”)};
$(“#slot4”)。单击(function(){$(“#content”).html(“”)};
现在,如果列表不断增长,这将变得单调和多余(想想slot57!)。如何写得更灵活优雅
到目前为止,我考虑将所有插槽id$('[id^=“slot”]')作为目标,并对索引(4)进行切片,以获得实际的点击数。但是如何加载正确的iframe内容呢
我卡住了。有什么想法/建议吗?如果您能够对标记进行一些修改,那么您可以尝试在标记中这样做:
<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代码:
$('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) +'">');
});
$('a[id^="slot"]').on('click', function(e){
e.preventDefault(); // stops the jump of anchor
$("#content").html('<iframe src="http://www.'+ $(this).data('url') +'">');
});
$('a[id^=“slot”]”)。在('click',函数(e)上{
e、 preventDefault();//停止锚点的跳转
$(“#内容”).html(“”);
});
你可以试试这个
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();
});
$('a')。单击(函数(e){
$(“#内容”).html(“”);
e、 预防默认值();
});
<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>
$('a').click(function(e){
$("#content").html('<iframe src='+$(this).attr('href')+'>');
e.preventDefault();
});