简体   繁体   中英

onblur and onfocus after javascript issue

I have an input form

<input id="txtSearch" class="txtSearch" name="SearchPhraseText" type="text"http value="<%= ServiceSite.Resources.Resources.SITEMATER_ENTER_SEARCH_TERM %>" onfocus="handleSearchFocus(this)" onblur="handleSearchBlur(this)" onkeypress="if (event.keyCode == 13 ) {search();}"/>

When I add the following to $(document).ready in my javascript..

if ( window.location.search.indexOf( "search" ) != -1){
    $('#txtSearch').val( "<%= Session["SearchPhrase"] %>"v);
}

given that I have this elsewhere in my javascript

     function handleSearchFocus(searchBox) {

        if ($(searchBox).val() == "<%= ServiceSite.Resources.Resources.SITEMATER_ENTER_SEARCH_TERM%>") {
           $(searchBox).val("");
           $(searchBox).css("color", "black");
        }

    }

    function handleSearchBlur(searchBox) {
        if ($(searchBox).val() == "" ) {
           $(searchBox).css("color", "gray");
           $(searchBox).val("<%= ServiceSite.Resources.Resources.SITEMATER_ENTER_SEARCH_TERM%>"); //should reference config file
        }

    }

Those two functions for handling focus and blur no longer work. The aren't run when I click on the input box or click away. What I'm trying to do is if there is a search value that should be displayed, display it. If not, it follows the logic in the blur/focus functions above.

I tried putting your code in jsFiddle here and got the following errors in the Developer Tools console:

Uncaught ReferenceError: handleSearchFocus is not defined

Uncaught ReferenceError: handleSearchBlur is not defined

Note that I set jsFiddle to run the script onLoad , which is what I'm assuming you're doing with your code.

Usually, you would run your code onLoad because you need all the elements to finish loading in order to manipulate and grab the elements on the page. In your situation, you need the opposite to happen. Your elements are created with your onfocus and onblur events tied to your functions. However, those functions do not exist yet and so they cannot be fired. Notice that your functions work if you change the jsFiddle onLoad to no wrap (body) .

In other words, the elements are trying to find the functions before they are available .

You need to either put your functions in <script> tags in the body (after the element), or attach it to the event in your $(document).ready code, like so:

$('#txtSearch').focus(function () {
    // code here
});
$('#txtSearch').blur(handleSearchBlur);

MrOBrian在问题注释中发现了导致此问题的错误。

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