当iframe名称是动态时的目标iframe



我的问题是针对iframe,其中添加了jQuery的动态名称。看来,当我尝试动态地将名称添加到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添加名称(

我仍然对默认行为感到困惑。似乎是避免弹出阻滞剂的新方法。

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

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

我通过设置iframe name下一个呼叫dom函数替换为替换iframe以替换自身的iframe function。然后它起作用。

在纯javascript中

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

最新更新