简体   繁体   中英

function in javascript not working when called

I have a javascript code that works by removing the first and the last line of it.

Please take a look at JSFiddle

for people who wants to see it in here, here is my html:

<input id="search" onclick="search()" type="button" value="Search"/>

my javascript :

    function search() {
var search = document.getElementById('search');

var int = setInterval(function() {
    if (search.value.length == 6)
        search.value = 'Searchi';
    else if (search.value.length == 7)
        search.value = 'Searchin';
    else if (search.value.length == 8)
    search.value = 'Searching';
    else {
        search.value= 'Search';
            }
    //clearInterval( int ); // at some point, clear the setInterval
}, 500);

}

I want the function to work only when I click the button.

You've selected jQuery in jsfiddle.net which by default causes the site to wrap your whole code in a document.ready handler.

The result is that your search function becomes a local function within that wrapper, and not a global variable as required by a DOM0 onclick handler.

Set the jsfiddle options to "no wrap (body)" and "No-Library (pure js)" to turn off that functionality.

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