简体   繁体   中英

Failing to trigger the onChange event

I've got this piece of code, to search the contents of HTML elements with the class "widget" and use the jQuery functions fadeIn() and fadeOut() to only show elements that match the search term. I don't know how to assign the search function to, because I don't assign it to the search box's change event. What is the equal of onchange= in jQuery? My current code:

function search(text, elements) {
    var term = text.value.toLowerCase();
    var elms = $(elements);
    var elm;
    for (var i = elms.length; i > 0; i-=1){
        elm = elms.get(i);
        if (elm.text().toLowerCase().indexOf(term)>=0 ) {
            elm.fadeOut(500);
        } else {
            elm.fadeIn(500);
        }

    }
}

And the failing inline script to trigger the onchange:

<script type="text/javascript">
    $(document).ready(function() {
    $("#search").change(function() {
            search($("#search").text(),".widget");
        });
    });

我会使用keyup()而不是change,Change仅在模糊时触发。

$("#search").change(function() { search($("#search").text(),".widget"); });

.change() is a reference to the .on() function in JQuery, so if you would like you could rewrite it this way :

$("#search").on('change' , function(){ search($(this).val(),".widget"); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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