猿问

使用JavaScript将参数从表单发送到函数

我正在尝试将值从表单发送到打开的新窗口。在我的程序中,窗口打开,但未val2发送值,而是存在null。


我的代码:


function eq(value) {

  ViewImg = window.open('http://localhost/coord.php?' + value, 'ViewImg', 'width=<?php print $realWidthNewWindow; ?>,height=<?php print $realHeightNewWindow; ?>', 'status=no', 'titlebar=0');

}

<form id='testform_eq' name='testform_new'>

  <input type='text' id='val2' name='val2'>

  <input type='button' value='Submit' onclick='eq(document.getElementById(val2))'>

</form>

有谁知道为什么会这样吗?谢谢


元芳怎么了
浏览 179回答 3
3回答

当年话下

如果要传递输入值,则应考虑两点:getElementById 接受一个字符串,但是您正在尝试传递一个不存在的变量如果要传递值而不是元素,则应.value在该元素之后添加最后,您应该具有以下input元素:<input type='button' value='Submit' onclick='eq(document.getElementById("val2").value)'>这是一个实时示例:<script>function eq(value) {&nbsp; console.log(value);&nbsp; ViewImg = window.open('http://localhost/coord.php?' + value, 'ViewImg', 'width=<?php print $realWidthNewWindow; ?>,height=<?php print $realHeightNewWindow; ?>', 'status=no', 'titlebar=0');}</script><form id='testform_eq' name='testform_new'>&nbsp; <input type='text' id='val2' name='val2'>&nbsp; <input type='button' value='Submit' onclick='eq(document.getElementById("val2").value)'></form>另一种选择是让里面的函数值,如所描述这里。如果您不打算重复eq使用不同的值,则这种方法很好。您必须根据实际情况选择其中之一。

潇潇雨雨

function eq() {&nbsp; const value = document.getElementById('val2').value;&nbsp; ViewImg = window.open('http://localhost/coord.php?' + value, 'ViewImg', 'width=<?php print $realWidthNewWindow; ?>,height=<?php print $realHeightNewWindow; ?>', 'status=no', 'titlebar=0');}<form id='testform_eq' name='testform_new'>&nbsp; <input type='text' id='val2' name='val2'>&nbsp; <input type='button' value="Submit" onclick='eq()'></form>您无需将任何内容传递给click函数。由于您已经具有输入元素的id属性,因此单击时可以获得输入的值。可能您想在其他地方使用该函数,这意味着您每次必须传递该元素。如果您确实想传递某些内容,则可以传递id本身。eq('val2')eq函数看起来比:function eq(id){&nbsp; const value = document.getElementById(id).value;&nbsp; ....}比起您可以在其他输入的其他位置使用该功能。

凤凰求蛊

因为您应该这样做: document.getElementById("val2").valuedocument.getElementById(val2)如果要获取id=val2值,则不正确。要修复它,您可以替换eq(document.getElementById(val2)成eq(document.getElementById("val2").value)function eq(value) {&nbsp; ViewImg = window.open('http://localhost/coord.php?' + value, 'ViewImg', 'width=<?php print $realWidthNewWindow; ?>,height=<?php print $realHeightNewWindow; ?>', 'status=no', 'titlebar=0');&nbsp; console.log(value);}<form id='testform_eq' name='testform_new'>&nbsp; <input type='text' id='val2' name='val2'>&nbsp; <input type='button' value='Submit' onclick='eq(document.getElementById("val2").value)'></form>或者只是将id放在函数调用中: eq(val2)function eq(id) {&nbsp; ViewImg = window.open('http://localhost/coord.php?' + id.value, 'ViewImg', 'width=<?php print $realWidthNewWindow; ?>,height=<?php print $realHeightNewWindow; ?>', 'status=no', 'titlebar=0');&nbsp; console.log(id.value);}<form id='testform_eq' name='testform_new'>&nbsp; <input type='text' id='val2' name='val2'>&nbsp; <input type='button' value='Submit' onclick='eq(val2)'></form>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答