首页 > 解决方案 > 使用 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  
        }  
    } 


标签: javascripthtmlforms

解决方案


CSS 选择器

Document.querySelectorAll()

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")
  }
});

推荐阅读