当iframe名称为动态

时间:2019-05-17 16:43:04

标签: javascript jquery html iframe

我的问题是使用从jquery添加的动态名称来定位iframe。看来,当我尝试向iframe动态添加名称时,针对iframe的链接会在新窗口中打开。

测试代码很简单:

html:

<a href="https://www.gaugeonline.com/" target="iframe1">test</a>
<iframe src="https://test.com"></iframe>

jquery:

$('iframe').attr('name', 'iframe1');

我做了一个简单的小提琴:https://jsfiddle.net/2ztg7xpj/1/

我还尝试过动态添加目标和名称:

html:

<a href="https://www.gaugeonline.com/">test</a>
<iframe src="https://test.com"></iframe>

jquery:

$('iframe').attr('name', 'iframe1');
$('a').attr('target', 'iframe1');

和小提琴:https://jsfiddle.net/2ztg7xpj/2/

问题是,为什么这是动态添加的iframe名称的行为,并且有一些解决方法(除了直接将名称添加到iframe之外)

2 个答案:

答案 0 :(得分:1)

我仍然对默认行为感到困惑。似乎是一种避免弹出窗口阻止程序的新方法。

无论如何,我都创建了自己的解决方法。

$('a[target=frame1]').click( function( e ) {
    e.preventDefault();
    var href= $(this).attr('href');
    $('iframe[name=frame1]').attr('src', href);
});

答案 1 :(得分:0)

我通过在设置iframe名称之后接下来调用DOM函数replaceWith来替换iframe来解决这个问题。然后就可以了。

在普通JavaScript中,类似

{
    const iframe = document.querySelector('iframe');
    iframe.name = 'iframe1';
    iframe.replaceWith(iframe);
}