【问题标题】:Form Input Name (Instagram)表单输入名称 (Instagram)
【发布时间】:2021-09-23 11:45:52
【问题描述】:

我是 HTML/CSS 新手,遇到一个问题,我无法通过 Google 搜索解决。

我已经设置了一个搜索框,可以将您带到谷歌。

<form action="https://www.google.co.uk/search"target="_blank">
        <input type="text" name="q">
        <button>Search Google</button>
    </form>

这适用于谷歌,你可以输入搜索,点击按钮,它会将你带到谷歌搜索。

但是当我在 Instagram 上尝试相同的操作时,它会将我带到一个错误页面。

    <form action="https://www.instagram.com/explore/tags/"target="_blank">
        <input type="text" name="q">
        <button>Search instagram</button>
    </form>

例如,如果您输入#Coding,它会将您带到此页面: https://www.instagram.com/explore/tags/?q=%23coding

而不是这个页面: https://www.instagram.com/explore/tags/coding/

不确定我做错了什么,请有任何建议帮助我:)

【问题讨论】:

    标签: html forms input


    【解决方案1】:

    Google 接受 GET 参数 q 作为要搜索的字符串。所以你的第一个表格可以根据需要工作。 而 instagram 将搜索查询添加到 URL。

    你需要一点 JS 的帮助来让你的第二种形式根据需要工作:

    const form = document.querySelector("form");
    const q = document.querySelector("input[name='q']");
    
    
    form.addEventListener("submit", (event) => {
      event.preventDefault();
      
      const url = form.action + '/' + q.value;
      
      window.open(url);
    });
    

    工作示例:https://jsfiddle.net/asertfy5/1/

    【讨论】:

    • 感谢 iPasha 这行得通,但是有没有办法标记这个 JS 代码,所以它只适用于 Instagram 表单而不是页面上的其他表单?
    • @HelloWorld 将 id 添加到 instagram 表单,然后仅将事件监听器绑定到具有指定 id 的表单
    【解决方案2】:

    下面是一种方法,似乎可以满足您的书面要求;解释在代码中作为 cmets:

    // defining a named handler for the <form> element's submission, using
    // Arrow syntax, and passing the Event Object automagically from the
    // (later) use of EventTarget.addEventListener():
    const formHandler = (event) => {
      // here we make use of the event.preventDefault() method to
      // prevent the <form> from being submitted:
      event.preventDefault();
      // we get a reference to the current <form> element to which the
      // event-handler is bound:
      let form = event.currentTarget,
        // an Object of functions to handle the submission process,
        // based on the supplied attribute-value of the custom
        // data-* attribute in the <form> tag:
        format = {
          getParameters: function() {
            // if GET parameters are used then we can simply
            // submit the <form> programatically, taking
            // advantage of the fact that programmatic events
            // don't call event-handlers by default, so this
            // submission bypasses the <form> element's
            // submit-handler:
            form.submit();
          },
          rest: function() {
            // if we're accessing a REST API, then we simply
            // use Window.open(), and pass the relevant URL string;
            // this function has access to the variables declared
            // outside of itself, so here we create the URL by
            // retrieving the path from the <form> element's
            // action attribute and concatenating that with the
            // trimmed value of the <input> element with the
            // name of 'q' (this is not designed to handle multiple
            // words, however; if that's a requirement please leave
            // a comment but that's not ordinarily how a REST API
            // would work):
            window.open(`${form.action}${form.q.value.trim()}`);
          }
        };
      // here we call the function held within the format Object,
      // after determining the appropriate search-method from the
      // <form> element's custom data-searchmethod attribute and
      // using bracket-notation, in place of dot-notation, to access
      // that function:
      format[form.dataset.searchmethod]();
    };
    
    // we iterate over all <form> elements using document.querySelectorAll() to
    // retrieve those elements, and then chaining with NodeList.prototype.forEach()
    // to handle iteration:
    document.querySelectorAll('form').forEach(
      // here we pass the current <form> element into the function,
      // and bind the formHandler() function as the event-handler for
      // the 'submit' event on that <form>:
      (form) => form.addEventListener('submit', formHandler)
    );
    /* all CSS is irrelevant, it's just to make the demo
       a little prettier */
    *,
     ::before,
     ::after {
      box-sizing: border-box;
      font-size: 1rem;
      font-weight: 400;
      line-height: 1.5;
      margin: 0;
      padding: 0;
    }
    
    form {
      display: flex;
      gap: 0.25em;
      justify-content: start;
      margin-block: 1em;
      margin-inline: auto;
      width: 80vw;
    }
    
    button {
      padding-inline: 0.3em;
    }
    <!-- within the <form> element's opening tag I added a custom data-*
         attribute to provide information about how the search functionality
         is intended to work, in the case of Google we're using, and therefore
         passing, GET parameters: -->
    <form action="https://www.google.co.uk/search"
      target="_blank"
      data-searchmethod="getParameters">
      <input type="text" name="q">
      <button>Search Google</button>
    </form>
    
    <!-- in the Instagram search, we're using a REST endpoint: -->
    <form action="https://www.instagram.com/explore/tags/" target="_blank" data-searchmethod="rest">
      <input type="text" name="q">
      <button>Search instagram</button>
    </form>

    JS Fiddle demo.

    请注意,虽然上面的代码在 JS Fiddle 和 Stack Snippet 之间是相同的,但由于沙盒的安全限制,Snippet 在 Stack Overflow 上无法运行,因此请在链接的 JS Fiddle 中进行测试。

    我觉得值得补充的是,在我的测试过程中,Instagram 的 URL 是根据您的需要创建的,但是 Instagram 网站阻止了该页面的加载。这可能是也可能不是我的结果,但是虽然我可以验证打开页面的 URL 是否与您的请求相匹配,但我无法验证它是否加载了您想要的内容。

    参考资料:

    【讨论】:

    • 嗨大卫哇,非常感谢你花时间解释一切,我发现这很有帮助。一件事,当你尝试以这种方式搜索时,你会在 Instagram 上被屏蔽吗?我在 Chrome 和 Firefox 上被屏蔽了这条消息。 www.instagram.com 被阻止www.instagram.com 拒绝连接。 ERR_BLOCKED_BY_RESPONSE
    • 是的,这就是答案中最后一段的内容。
    • 感谢大卫的所有帮助 :)
    猜你喜欢
    • 2011-11-09
    • 2013-06-14
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2012-03-29
    • 2013-02-17
    • 2013-05-13
    • 2017-10-27
    相关资源
    最近更新 更多