改进点:支持同页面有多个文本框,可自动向不同的文本框传值。先看演示吧
其实原理也很简单。同样先通过getAttribute判断type属性,捕捉到按钮。然后在按钮onclick时把i通过url传入子页面。
代码如下:
| 1 | <h2>input1</h2> |
| 2 | <input type="text" /><input type="submit" /> |
| 3 | <h2>input2</h2> |
| 4 | <input type="text" /><input type="submit" /> |
| 5 | <script type="text/javascript"><!-- |
| 6 | var aInput = document.getElementsByTagName("input"); |
| 7 | for (i = 0 ; i < aInput.length ; i++ ) |
| 8 | { |
| 9 | ( |
| 10 | function (i){ |
| 11 | if (aInput[i].getAttribute("type") == "submit") |
| 12 | { |
| 13 | aInput[i].onclick = function (){ |
| 14 | window.open('b.html?'+i,'newwindow','height=100,width=400') |
| 15 | } |
| 16 | } |
| 17 | } |
| 18 | )(i) |
| 19 | } |
| 20 | // --></script> |
子页面用slice方法对url进行切分。并使用window.opener方法捕捉到父页面的文本框,进行赋值。 一切就OK了
代码如下:
| 1 | <h2>openWindow</h2> |
| 2 | <input type="text" /><input type="submit" /> |
| 3 | <script type="text/javascript"><!-- |
| 4 | var aInput = document.getElementsByTagName("input"); |
| 5 | for (i = 0 ; i < aInput.length ; i++ ) |
| 6 | { |
| 7 | if (aInput[i].getAttribute("type") == "text") var textboxB = new Object(aInput[i]); |
| 8 | if (aInput[i].getAttribute("type") == "submit") var btnB = new Object(aInput[i]); |
| 9 | } |
| 10 | btnB.onclick = function(){ |
| 11 | var sTextValue = textboxB.value |
| 12 | var aInput = window.opener.document.getElementsByTagName("input"); |
| 13 | var sUrl = document.location; |
| 14 | var sNo = sUrl.toString().slice(-1) |
| 15 | window.opener.aInput[sNo-"1"].value = sTextValue |
| 16 | window.close(); |
| 17 | } |
| 18 | // --></script> |

浙公网安备 33010602011771号