2017-06-01 128 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

是的,認爲如此,這是它最初是如何設置與兩個不同的腳本文件。從那裏調用子窗口的功能。掙扎..也許你知道一個解釋的鏈接?如果不感謝您的幫助,不管! –