javascript - 使用 GET METHOD 选择表单
问题描述
我下面的代码选择具有 POST 和 GET 方法的表单。但我只想选择带有 GET 表单方法属性的表单。如何使用选择器/过滤器仅检索将表单方法设置为 GET 的表单元素
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
{
const {
document
} = (new JSDOM(data)).window;
var all = document.getElementsByTagName("FORM");
for (var i = 0, max = all.length; i < max; i++) {
var aform = document.getElementsByTagName("FORM")[i];
// log aform.outerHTML
}
}
解决方案
let getform = document.querySelectorAll("form[method=GET]")[0].id;
console.log(getform)
let postform = document.querySelectorAll("form[method=POST]")[0].id;
console.log(postform)
let omittedform = document.querySelectorAll("form")[2];
if (!omitted.getAttribute("method")) {
console.log(omitted.id)
}
[...document.querySelectorAll("form")].forEach(form => {
if (!form.getAttribute("method") || form.getAttribute("method") === "GET") {
console.log("Form with id " + form.id + "is GET")
} else if (form.getAttribute("method") === "POST") {
console.log("Form with id " + form.id + "is POST")
}
});
<form method="GET" id="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
<form method="POST" id="post">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
<form id="omitted">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
正如评论所建议的,如果省略了表单方法,则需要检查 HTML 中是否存在方法属性,如果不存在,则可以将其视为 GET。
!omitted.getAttribute("method")
由于我们看不到您的 HTML,您需要使用上面的示例来编写适合您用例的自己的逻辑。
或者你可以像这样检查它:
[...document.querySelectorAll("form")].forEach(form => {
if (!form.getAttribute("method") || form.getAttribute("method") === "GET" ) {
console.log("Form with id " + form.id + "is GET")
} else {
console.log("Form with id " + form.id + "is POST")
}
});
推荐阅读
- javascript - 将变量设置为针对具有相同类的所有 div
- python - 散景——在需要的地方部分加载数据
- node.js - 在 where cluse 中续集文字字段
- python - 如何将值附加到 Flask-Sqlalchemy
- typescript - AWS Lambda(NodeJs)将项目放入 DynamoDB 中,地图包含动态键
- angular - 如何使用带有 HTML/组件的 ConfirmPopup (p-confirmpopup) 而不是字符串消息
- mysql - 如何在 MySQL 中查找两个日期之间的累积和?
- prometheus - 如何将具有不同标签的普罗米修斯时间序列的相同名称组合成一个指标?
- database - 将 FUNCTION 添加到只读事务(PGSQL 和 Docker 复制)
- javascript - 在 ReactJS 中只重定向一次