如何使用页面名称作为文本框的值
问题描述:
我试图用Javascript实现一些事情。我有点小菜,所以请忍受我。如何使用页面名称作为文本框的值
首先我用这个代码创建一个弹出窗口:
HTML:
<a href="JavaScript:newPopup('contact.html');"><img src="request.jpg"/></a>
JS:
var sPage;
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=400,width=800,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
window.name = sPage;
}
这部分工作正常,但就是我,然后试图做的是将当前页面名称放入'contact.html'中的文本框中。
这是我使用的弹出页面上,试图做到这一点的代码:
function add(text){
var TheTextBox = document.getElementById("prodcode");
TheTextBox.value = TheTextBox.value + window.name;
}
这似乎当它是我连接到正常页面的工作,但如果它是它不会工作一个弹出。我也无法弄清楚如何摆脱页面名称的扩展名。
我意识到有可能有一百万更好的方法来做到这一点,但这是对我来说似乎最有意义的方法。我看过饼干,但我似乎无法弄清楚。
我知道我问了很多,但任何帮助将不胜感激。
谢谢。
答
如果我正确理解问题,可以将该窗口名称作为查询参数传递给您传递给您的newPopup
函数的URL,然后将其在contact.html页面中抓取以放入框中。
例如,您newPopup
功能可以在查询参数添加到URL,像这样:
function newPopup(url) {
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
var windowName = sPage.split(".")[0];
popupWindow = window.open(url + '?window_name=' + windowName,'popUpWindow','height=400,width=800,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no');
window.name = windowName;
}
然后,在你的contact.html文件,设置文本框的值时抢查询参数,使用这种逻辑:
function parseURLParams(name, locat) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(locat);
if (results) {
return results[1] || "";
} else {
return "";
}
}
function add(text) {
var TheTextBox = document.getElementById("prodcode");
TheTextBox.value = TheTextBox.value + parseURLParams("window_name", window.location.href);
}
希望它有帮助!