jQuery input button click event listener

2020-02-17 06:34发布

Brand new to jQuery. I was trying to set up an event listener for the following control on my page which when clicked would display an alert:

<input type="button" id="filter" name="filter" value="Filter" />

But it didn't work.

$("#filter").button().click(function(){...});

How do you create an event listener for a input button control with jQuery?

3条回答
Juvenile、少年°
2楼-- · 2020-02-17 07:10

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

查看更多
干净又极端
3楼-- · 2020-02-17 07:20

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

查看更多
Rolldiameter
4楼-- · 2020-02-17 07:24
$("#filter").click(function(){
    //Put your code here
});
查看更多
登录 后发表回答