2017-06-01 41 views
1
<!--The element of images is the child window. I can get the javascript to work 
    correctly from the child window, but I need the class of the image clicke 
    on from the parent page to effect the child window using window.open.--> 

<div class="slides"> 
    <img class="item-1 cardone" src="images/cardone.jpg"/> 
    <img class="item-2 cardtwo" src="images/cardtwo.jpg"/> 
    <img class="item-3 cardthree" src="images/cardthree.jpg"/> 
    <img class="item-4 cardfour" src="images/cardfour.jpg"/> 
    <img class="item-5 cardfive" src="images/cardfive.jpg"/> 
</div> 


在点击传送的JavaScript从父窗口的子窗口中使用,window.open

$('.icon-search').click(newWindow); //targeting the image 

function newWindow(){ 
    var win = window.open('../carousel/index.html'); //child window 
    var script = document.createElement('script'); 
    var $this = $(this).prev().attr('class'); //class of image to save for child window 

    //script below pertains to only child window 
    $("."+newSrc+"").not(this).remove('img'); 
    $(this).insertAfter($('.slides img:nth-child(2)')).addClass('item-3'); 
    $('.slides img:nth-child(1)').removeClass().addClass('item-1'); 
    $('.slides img:nth-child(2)').removeClass().addClass('item-2'); 
    script.src = 'pf-js/projects.js'; 
    win.document.head.appendChild(script); 
} 

我需要的脚本调试,并在控制台检查时使用window.open,被转移,没有脚本被转移。

+0

试试这个:'win.document.getElementsByTagName( “头”)[0] .appendChild(脚本);' –

+0

@LouysPatriceBessette脚本不工作..我的不正确的底部看win.document.head.appendChild(脚本);从您的体验控制台日志应该显示在头部的新脚本? –

回答

1

您必须将脚本定义为字符串并将其附加到DOM节点。
然后,您可以将此DOM节点附加到新打开的窗口的头部。

我做了你一个简单的例子,在CodePen其中有这样的代码:(我只加一个按钮,你的HTML触发脚本)


<button class="icon-search">Icon Search</button>

MAKE SURE您将追加的脚本正在工作!
newSrc未定义(来自您发布的内容)。

// Button handler. 
$('.icon-search').click(newWindow); //targeting the image 

function newWindow(){ 

    // Create a script node 
    var script = document.createElement("script"); 

    // Define the script as a string. 
    var scriptText = 
     "alert('Hello World!');"+ 
     "var body = document.getElementsByTagName('body')[0];"+ 
     "body.style.backgroundColor = 'red';"+ 
     "body.innerHTML = '<h1>This works!</h1>'"; 

    // Put the script string inside the script node, 
    script.innerHTML = scriptText; 

    // Open a new window. 
    var newWin = window.open("","_blank"); 

    // Append the script in head. 
    newWin.document.head.appendChild(script); 
} 
+0

哇..我见过这么多的解释,但从来没有一个工作脚本,看看它究竟是如何工作的..太棒了!我尽我所能地提供了一个想法,让我知道我正在使用的是为什么newSrc不工作。此外,我认为更简单的方法是从子窗口调用父窗口函数,从您的经验是更容易的路线? –

+0

这取决于你想要做什么...当然,它会让脚本'A'成为许多子文档的位置(更容易维护),并且不会关心单引号。但是,您需要在子页面中使用脚本'B'来获取脚本'A' ...因此,这需要2个脚本来维护。如果脚本“A”也在父文档上运行,那就没问题了。你将不得不给''编写脚本'A'来调用它的'innerHTML'。 **但是你也可以创建一个单独的.js文件!**这将是一个更好的方法。 ;) –

+0

是的,认为如此,这是它最初是如何设置与两个不同的脚本文件。从那里调用子窗口的功能。挣扎..也许你知道一个解释的链接?如果不感谢您的帮助,不管! –

相关问题