有些链接无法在iframe中打开

时间:2017-10-05 07:44:58

标签: javascript jquery ajax

$('div#content a').attr('target', 'forceToIframeWindow');

$(document).on("click", 'div#content a', function(){
 var thisSrc = $(this).attr("href");
 $(document.body).append(
 $('<iframe />').attr({
  "name":"forceToIframeWindow", 
  "src":thisSrc
 }))
});

DOM看起来像这样,这里有链接:

<p><a href="http://example.com" target="forceToIframeWindow">Example</a></p>

以及不起作用的链接:

<p><a href="http://example.com" target="forceToIframeWindow"><img src="test.jpg"></a></p>

1 个答案:

答案 0 :(得分:0)

如果要阻止链接的默认行为,则应使用preventDefault方法

$(document).on('click', 'div#content a', function(e){
    e.preventDefault(); // Stops the default execution of a link. Which normally is to open in a new window
    var thisSrc = $(this).attr("href");
    $(document.body).append(
        $('<iframe />').attr({
            "name":"forceToIframeWindow", 
            "src":thisSrc   
        })
    );
});
相关问题