![](/img/trans.png)
[英]Javascript: "Mouseover" and "mouseout" event handlers work, but "mouseout" doesn't work properly when "mouseover" is replaced by "click"
[英]Script doesn't work when event is changed from "mouseover" to "click"
當我將事件更改為“單擊”而不是“鼠標懸停”時,以下腳本不起作用。 知道為什么嗎? 我的意思是,我不能將任何 JSON 數據發布到 JSON 存儲服務。
<script>
const button = document.getElementById("search-image")
const s = document.getElementById("s")
function SendData(){
var xhr = new XMLHttpRequest();
var url = "https://krat.es/xxxxx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
}
};
var data = JSON.stringify({"Text": s.value});
console.log(data)
xhr.send(data);
}
button.addEventListener("mouseover",SendData)
</script>
更新:HTML代碼
<form _lpchecked="1" action="/search" class="search-form" id="searchform" method="get">
<fieldset>
<input id="s" name="q" onfocus="if(this.value=='Search')this.value='';" onwebkitspeechchange="transcribe(this.value)" type="text" value="Search" x-webkit-speech="">
<button class="sbutton" id="search-image" style="border:0; vertical-align: top;background: transparent;"><i class="fa fa-search"></i></button>
</fieldset>
</form>
您的按鈕位於表單內。 因此,當您單擊表單按鈕時,它將被發送並且不允許您的 JavaScript 代碼運行。
所以以這種方式更改按鈕代碼
html:
/* type="button" */
<button type="button" class="sbutton" id="search-image" style="border:0; vertical-align: top;background: transparent;"><i class="fa fa-search"></i></button>
js:
button.addEventListener("click",SendData)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.