【问题标题】:Button click if specific url如果特定网址,请单击按钮
【发布时间】:2023-01-24 21:19:10
【问题描述】:

我试图确保在转到某个 url 时,页面上的按钮被按下,但由于某种原因它不起作用。

<script>
    let loginInp = document.querySelector('.login-form--hide');
    let emailInp = document.querySelector('.email-form--hide');
    let sendInp = document.querySelector('.send-form--hide');


    let loginLoc = window.localStorage.getItem('name');
    let emailLoc = window.localStorage.getItem('email');

    document.addEventListener("DOMContentLoaded", () => {

        if (window.location.href === 'https://url/success/') {
            loginInp.value = loginLoc;
            emailInp.value = emailLoc;

            console.log('Worked');

            //sendInp.click();


        }
     });




</script>

我究竟做错了什么?

【问题讨论】:

  • 到底是什么不起作用? console.log(document.location.href) 的输出是什么

标签: javascript


【解决方案1】:
let loginInp = document.querySelector('.login-form--hide');
let emailInp = document.querySelector('.email-form--hide');
let sendInp = document.querySelector('.send-form--hide');

let loginLoc = window.localStorage.getItem('name');
let emailLoc = window.localStorage.getItem('email');

window.addEventListener("load", () => {
    if (window.location.href === 'https://url/success/') {
        if (loginInp) {
            loginInp.value = loginLoc;
        }
        if (emailInp) {
            emailInp.value = emailLoc;
        }
        if (sendInp) {
            sendInp.click();
        }
    }
});

您正在使用 DOMContentLoaded 事件来检查 URL 并执行操作。当初始 HTML 文档已完全加载和解析时会触发此事件,而无需等待样式表、图像和子框架完成加载。但是您可能想改用 load 事件,它会在所有资源都已加载后触发。

此外,请确保您的脚本位于 body 标签的底部,或者在加载元素后放在 head 标签中,以便脚本可以使用这些元素进行交互。

【讨论】:

  • 这不是问题的答案。这甚至没有任何意义。 DOMContentLoaded 确保代码在成功加载 dom 后执行。无需使用 onload 处理程序,也无需将此脚本移动到任何地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多