<!--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传输脚本,在控制台上调试和检查时,不会传输任何脚本。
答案 0 :(得分:1)
您必须将脚本定义为字符串并将其附加到DOM节点 然后,您可以将此DOM节点附加到新打开的窗口的开头。
我在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);
}