简体   繁体   中英

How do I use jQuery from another file.js

I have a HTML file:

<!DOCTYPE html>
<html>
<head>
<title>Insert</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script type="text/javascript" src="js/jquery-1.10.1.js"></script>
<script type="text/javascript" src="js/controlla.js"></script>
</head>
<body>
<div id="insert">
<img src="css/images/logo.png" alt="Search Engine Logo" />
<input id="#textboxone" onkeyup="scova(event)" type="text"/>
</div>
</body>
</html>

I have inserted script reference in order (first jquery, second my function file). In my function file, there is function scova(event) from onkeyup event in inputbox, is not possible use jQuery reference $ .

For example:

function scova(e) {
var valore = document.getElementById('#textboxone').value;
var valjquiro = $('#textboxone').val();
console.log('il valore di javascript: ' + valore);
console.log('il valore di jaquirro: '+valjquiro);
};

And in the browser console (after the digit 'test') I get:

il valore di javascript: test
il valore di jaquirro: undefined 

How can I use JQuery in my function file? How to use $ reference of jquery in my controlla.js?

Change

<input id="#textboxone" onkeyup="scova(event)" type="text"/>

to

<input id="textboxone" onkeyup="scova(event)" type="text"/>

so that $('#textboxone') won't be an empty object.

Once you've done that, fix also document.getElementById('#textboxone') by removing the # .

从您的id属性中删除#或执行以下操作-

var valjquiro = $('#\\#textboxone').val();

您不需要将jQuery 包含在任何其他JavaScript文件中:只需将jQuery放在所有<script>标记的顶部,所有接下来导入的文件都可以访问该库。

Try wrapping up the code from your function file like this:

$(document).ready(function(){ put your code here })

Read more about this here: http://api.jquery.com/ready/

Your code is probably running before the DOM has fully loaded, in its current state, if I understood you correctly.

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