Javascript not executing when placed in external script file

天大地大妈咪最大 提交于 2019-12-11 22:09:31

问题


I'm building an ASP.NET MVC site where I need a tag editor, similar to the one used on Stack Overflow. I've already looked up how to accomplish the necessary autocompletion with jQuery UI, but I've run into a problem: when I place the script in an external .js file, it doesn't execute.

Here is my test.html:

<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Test</title> 
    <script src="http://jqueryui.com/jquery-1.4.2.js"></script> 
    <script src="http://jqueryui.com/ui/jquery.ui.core.js"></script> 
    <script src="http://jqueryui.com/ui/jquery.ui.widget.js"></script> 
    <script src="http://jqueryui.com/ui/jquery.ui.position.js"></script> 
    <script src="http://jqueryui.com/ui/jquery.ui.autocomplete.js"></script>
    <script src="jquery.tagautocomplete.js"></script>
    <script> 
    $(function() { bindAutoTagComplete('#birds'); })
    </script>
</head> 
<body> 
    <label for="birds">Birds: </label> 
    <input id="birds" size="50" /> 
</body> 
</html> 

Here's jquery.tagautocomplete.js:

function bindAutoTagComplete(item, otherRootDomain)
{
        function split( val ) {
            return val.split( / \s*/ );
        }
        function extractLast( term ) {
            return split( term ).pop();
        }

        $(item).autocomplete({
            source: function( request, response ) {
                $.getJSON('http://jqueryui.com/demos/autocomplete/search.php', {
                    term: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( " " );
                return false;
            }
        });
    }

What do you think may be causing this problem? I'm probably missing some closing parantheses/braces in the .js file...

Thanks in advance!


回答1:


You need to attach that event after the page is ready. #birds doesn't exist when it runs currently.

Something like

<script>
$(document).ready( function(){  bindAutoTagComplete('#birds'); } );

</script>


来源:https://stackoverflow.com/questions/3897150/javascript-not-executing-when-placed-in-external-script-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!