单击从父项 window 传输 javascript 以用于子项 window、window.open

On click transfer javascript from parent window to be used in child window, window.open

 <!--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>


$('.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传输脚本,在控制台调试检查时,没有传输脚本。

您必须将脚本定义为字符串并将其附加到 DOM 节点。
然后,你可以将这个 DOM 节点附加到新打开的 window.

的头部

我在 CodePen 上为您制作了一个简单示例,其中包含以下代码:

(我只在您的 HTML 中添加了一个按钮来触发脚本。)
<button class="icon-search">Icon Search</button>

确保您要附加的脚本有效!!!
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);
}