我已经找到了一个可能的解决方案的问题,但我在阅读之前已经尝试过建议的方法,它甚至说它不一致。所以我想我想知道为什么这不起作用:
$("img").click(function() {
var imgwindow = window.open('imgwin.html','','width=460,height=345');
alert(imgwindow.find("img").attr("src"));
});
目标是将新窗口的img
设置为与用户单击以打开新窗口的图像相同的src
。但在上面的场景中,我只是试图进入新窗口以获得它已经设置的src。我已为imgwin.html
编写了默认src
图片,因此它应该提醒该网址。相反,我得到undefined
。
我也尝试了以下(后端应该相同),但结果相同:
$("img").click(function() {
var imgwindow = window.open('imgwin.html','','width=460,height=345');
alert($("img",imgwindow).attr("src"));
});
我甚至试过在imgwindow
中包装$()
变量的变体,以防某些jquery没有将变量作为DOM元素接收。
我唯一可以猜到的是,因为window.open()
是一个方法,所以jquery并不像对待DOM元素那样,即使基本javascript教程中的所有文档都将变量视为打开的方法窗口和指向窗口内部DOM的指针。
我通常更喜欢并向其他开发人员推荐使用jquery-ui对话框小部件,但在这种情况下,图像实际上是用户希望弹出主窗口并且即使主窗口关闭,所以虽然我很欣赏弹出窗口的移动,但请避免建议涉及同窗口小部件的替代方案。感谢。
答案 0 :(得分:2)
为什么不这样做呢
$("img").click(function(e) {
var src = $(this).attr('src');
window.open(src,'','width=460,height=345');
});
这将打开一个新窗口,里面有你的图片! ; - )
在回复您的评论时,需要执行以下操作:
$("img").click(function(e) {
//Load content in your page and hide it...
$('#result').load('imgwin.html').hide();
//find the image you want...
alert($('#result').find("img").attr("src"));
//remove it from your page..
$('#result').remove();
});
更新2
好的,还是这个,我喜欢它! ; - )试试这个:
var reg = /src=\"(.+[\.jpg|\.jpeg|\.png|\.gif])\"/;
var imgwindow = $.ajax({type: "GET", url: "imgwin.html", async: false }).responseText;
var img = imgwindow.match(reg)[1];
alert(img);
答案 1 :(得分:2)
快速而肮脏
var src = '';
var imgwindow;
$(function() {
$("img").click(function() {
imgwindow = window.open('urlto.html','','width=460,height=345');
src = this.src;
//delay needed as I couldn't manage to get ready/load events to work on the
//imgwindow.document object
//thus the snippet is dirtier then need with all those "global" variables
setTimeout('$("img", imgwindow.document.body).attr("src", src)', 1000);
});
});
注意:仅在Opera中测试过。 imgwindow.document
可能不适用于所有浏览器。至少我记得iframe存在问题,其中需要document / contentDocument和其他“标识符”来获取新窗口/ iframe的“文档”。但只需在您需要支持的任何浏览器中进行测试