简体   繁体   中英

Javascript works but JQuery does not?

My code is like this:

<script> 
    var name = document.getElementById("nusname").innerHTML;
    document.getElementById("uName").innerHTML = "Welcome, " + name;
    $('#uName').text("AsgufHFBS");
</script>

The 3rd line

document.getElementById("uName").innerHTML = "Welcome, " + name;

works but the 4th line

$('#uName').text("AsgufHFBS");

does not.

I have tried replacing this with

$(document).ready(function(){
    $('#uName').text("AsgufHFBS");
});

but it still does not work.

So my question is this: Why does the javascript work but the not the JQuery version?

Add this in the <head> of your document:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Or simply update your code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script> 
    var name = document.getElementById("nusname").innerHTML;
    document.getElementById("uName").innerHTML = "Welcome, " + name;
    $('#uName').text("AsgufHFBS");
</script>

Assuming that you have already embedded the jQuery library correctly and it's still not working, try this:

jQuery('#uName').text("AsgufHFBS");

If that works it means the $ shorthand is likely reserved by another script on your page. You can either correct that issue, or just preface jQuery commands with "jQuery" rather than "$" on that page.

I have coded your code into jsFiddle and it works fine, however did you include jQuery in your file? If you press f12 in your browser do you get any console logs? If so please provide them.

But here is the jsFiddle version which does include jQuery

jsFiddle : https://jsfiddle.net/bn788ff4/

Html

<div id="nusname">hello</div>
<div id="uName">username</div>

Javascript / jQuery

var name = document.getElementById("nusname").innerHTML;
document.getElementById("uName").innerHTML = "Welcome, " + name;
$('#uName').text("AsgufHFBS");

To include jQuery you can use the hosted version by google

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Link https://developers.google.com/speed/libraries/

You are probably missing Jquery library files. Please attach the foolowing to the <head> section of your page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

and replace the 4th line of your code with:

$('#uName').html("AsgufHFBS"); 

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