ReferenceError:赋值JavaScript中的左侧无效

时间:2018-06-15 08:13:14

标签: javascript html

我正在尝试使用JavaScript将操作分配给HTML表单,但是,我得到了ReferenceError:赋值中的左侧无效。

我的代码:

<form action="/" method="POST" name="search-theme-form" id="search-theme-form" >
User <input type="text" name="user" />
Term<input type="text" name="term" />
Subject<input type="text" name="subject" />
Grade<input type="text" name="grade" />
Marks<input type="text" name="marks" />
<script>
var params = (new URL(document.location)).searchParams;
var studentId = params.get("stdid");
var studentId = params.get("stdid");
var x = "app/students/"  + studentId;
document.search-theme-form.action = x;
</script>
    <input id="submitButton"  type="submit"value="Submit" />
</form>

2 个答案:

答案 0 :(得分:3)

如果密钥中包含dot (.),则无法使用hyphen运算符。使用bracket notation []访问属性。

document["search-theme-form"].action = x;

答案 1 :(得分:2)

您需要使用document.querySelector('[name="search-theme-form"]')来获得更好的方法。此外,请始终检查浏览器的console以检查错误并尝试解决该错误。问题是您没有选择form元素,因此使用document.querySelector('[name="search-theme-form"]')会选择form元素,然后将action添加到其中。因此,document.search-theme-form.action在左侧是undefined,因为您需要使用document['search-theme-form'].action

var params = (new URL(document.location)).searchParams;
var studentId = params.get("stdid");
var studentId = params.get("stdid");
var x = "app/students/"  + studentId;
document.querySelector('[name="search-theme-form"]').action = x;
<form action="/" method="POST" name="search-theme-form" id="search-theme-form" >
User <input type="text" name="user" />
Term<input type="text" name="term" />
Subject<input type="text" name="subject" />
Grade<input type="text" name="grade" />
Marks<input type="text" name="marks" />

相关问题