繁体   English   中英

在 JQuery 和 vanilla JS 之间设置 function 时可能发生冲突?

[英]Possible conflict while setting function between JQuery and vanilla JS?

我正在尝试在 JS 和 PHP 中制作自己的盗版 bash 克隆,但我遇到了一个问题。 尝试执行此脚本时,错误日志告诉我输入的命令()未定义,即使您可以看到它位于表单上方。

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(function(){
        if($(".command") !== null){
            function enteredCommand(){
        }
        } else{
            // do nothing
        }
    });
</script>
<form id="commandField" onsubmit="return enteredCommand();">
    <p>bbash~ User:</p>
    <input class="command" type=text>
</form>

请帮忙。 我是新人,这不是重复的。 因为我看不出它是如何定义的,是的。 控制台指定错误发生在“onsubmit”。

这是因为您已经定义了onsubmit调用的 scope 中的输入enteredCommand() function。

您需要反转逻辑,以便if条件在输入的enteredCommand() function 内。 还要注意在 JS 代码中使用不显眼的事件处理程序。 onX属性添加到 HTML 不再是好的做法,应该避免。

最后,要从 jQuery object 中检索值,您需要调用val() Comparing a jQuery object to null will never be true, as a jQuery object is never null.

 let execCommand = c => { console.log(`User entered '${c}', handle it here...`); } $(function() { let $command = $('.command'); $('#commandForm').on('submit', e => { e.preventDefault(); // stop the form submission so you can handle it manually let command = $command.val().trim(); if (command) execCommand(command); }); });
 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <form id="commandForm"> <p>bbash~ User:</p> <input class="command" type="text" /> </form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM