gpt4 book ai didi

javascript - 如何在javascript中同时使用输入按钮和onclick(鼠标单击)

转载 作者:行者123 更新时间:2023-12-03 00:13:21 25 4
gpt4 key购买 nike

我正在尝试触发 ajaxFunction()单击鼠标并在提交按钮上“输入 key ”。下面是我的代码

<html>
<body>
<script language = "javascript" type = "text/javascript">

//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!

try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {

// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {

try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}


ajaxRequest.onreadystatechange = function() {

if(ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}


var wpm = document.getElementById('wpm').value;

var queryString = "?wpm=" + wpm ;


ajaxRequest.open('GET', 'ajax-example.php' + queryString, true);
ajaxRequest.send(null);
}

</script>
<script>
const textbox = document.getElementById("wpm");
textbox.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
document.getElementById("cli").click();
}
});
</script>
<form name = 'myForm'>

Max WPM: <input type = 'text' id = 'wpm' /> <br />


<input type = 'button' id="cli" onclick = 'ajaxFunction()' value = 'Query MySQL'/>
</form>

<div id = 'ajaxDiv'>Your result will display here</div>
</body>
</html>

我按下回车键,就像

http://localhost/myphp/ajax.html?
with a blank page

onclick工作正常。但奇怪的是 onclick 不适用于 <input type = 'submit' id='cli' onclick = 'ajaxFunction()' value = 'Query MySQL'/>但适用于 <input type = 'button' id='cli' onclick = 'ajaxFunction()' value = 'Query MySQL'/>

最佳答案

在 dom 中定义 id 为“wpm”的输入元素之前,您的 Enter 键按下事件监听器脚本将被执行,可能是因为您的 dom 操作脚本阻止了文档被解析。

尝试将此脚本放在正文关闭之前,如下所示:

  <div id = 'ajaxDiv'>Your result will display here</div>
<script>
const textbox = document.getElementById("wpm");
textbox.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
document.getElementById("cli").click();
}
});
</script>

关于javascript - 如何在javascript中同时使用输入按钮和onclick(鼠标单击),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54624363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com