ajax,用两个事件启动函数

ajax, start function with two events

本文关键字:两个 事件 启动 函数 ajax      更新时间:2023-09-26

我有一个函数,需要在单击或按Enter键时开始。所以我需要这样的东西:

<BUTTON onclick="searchProduct()" or onkeypress="searchProduct()">Hledat</BUTTON>

但只能在按Enter键时。没有钥匙。

这对于Ajax或纯javascript来说可能吗?

好吧,没想到它这么复杂,所以我把我的全部代码都给了你,因为你的答案不适用于我的整个代码。。。

<!DOCTYPE html>
<HTML>
    <HEAD>
        <META charset="UTF-8" />
        <TITLE>Searchin engine</TITLE>
    </HEAD>
    <BODY>
        <SCRIPT src="js_search.js"></SCRIPT>
        <FORM>
            <INPUT type="text" id="word" size="40" />
        </FORM>
         <BUTTON onclick="searchProduct(document.getElementById('word').value)">Hledat</BUTTON>
        <P id="display"></P>
    </BODY>
</HTML>

只需在javascript中添加事件侦听器(例如,在searchProduct()函数上方)

document.getElementById('button').addEventListener('click', function(){
  searchProduct(document.getElementById('word').value);
})
document.getElementById('button').addEventListener('keydown', function(e){
  if(e.keyCode == 13) searchProduct(document.getElementById('word').value); // the keyCode 13 is equivalent to the enter key
})
function searchProduct(val) {
  alert(val);
}
<button id="button">Hledat</button>
<input id="word" value="foo"/>

希望这能有所帮助!

理想情况下,元素和enter上应该有单独的事件,您可以调用特定的函数,也可以触发元素的单击。

如果您希望输入和按钮点击工作相同,我建议触发点击事件。这将确保更新所有UI状态并完成所有处理。原因是,我们可以为一个按钮添加多个处理程序以进行不同的处理,并且调用函数可能不会调用其他代码。

function keyPress(e) {
  if (e.keyCode == 13) {
    document.getElementById("btn").click();
  }
}
function notify() {
  console.log("Processing...")
}
<input type="text" id="txt" onkeyup="keyPress(event)">
<button id="btn" onclick="notify(event)">Notify</button>

你可以做:

<BUTTON onclick="searchProduct()"  onkeypress="searchProductKeyPress(event)">Hledat</BUTTON>
function searchProductKeyPress(event) {
    if (event.which == 13 || event.keyCode == 13) {
        searchProduct();
        return false;
    }
    return true;
}

在函数中,您可以传递如下事件:

<BUTTON onclick="searchProduct(event)" onkeypress="searchProduct(event)">Hledat</BUTTON>

现在在功能中:

searchProduct(e){
    if(e.type === 'keypress' && e.keyCode !== 13){
        return;
    }    
    // put the code for search here.
}

将id="btn_search_product"设置为按钮

var btn_search_product = document.getElementById("btn_search_product");
btn_search_product.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
        searchProduct(e);
    }
});

我实际上使用evento库https://github.com/petermichaux/evento

有了它,它将是:

evento.add(btn_search_product, "keydown", function (e) {
        if (e.keyCode === 13) {
            searchProduct(e);
        }
});