ChatGPT解决这个技术问题 Extra ChatGPT

Why is this jQuery click function not working?

Code:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $("#clicker").click(function () {
        alert("Hello!");
        $(".hide_div").hide();
    });
</script>

The above code doesn't work. When I click on #clicker, it doesn't alert and and it doesn't hide. I checked the console and I get no errors. I also checked to see if JQuery was loading and indeed it is. So not sure what the issue is. I also did a document ready function with an alert and that worked so not sure what I am doing wrong. Please help. Thanks!

Wrap the code in document.ready
did u checked the browser's console if there are any errors, syntax or file not found or something else?

m
mobius

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

i.e.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"


How stupid of me!! Still learning. I thought I click function doesn't need one since it's activated on clicking vs document.ready where it loads on page load.
@starbucks Don't worry about it too much, everyone makes mistakes, and especially when learning :)
The document ready function sets up the listeners based on what it finds on the page. If you don't do this, they are never set up. The best way to do this, however, is to delegate them with the "on()" function, instead. That way any elements added to the page after load will still work!
Also, with the "on" function, you don't actually need to use the document ready function. It sets the listener to document level, and then scrapes the page for the elements to listen to. That's why it's a little faster to be a little more specific about what element type you want to listen to, like "div.listentome" as opposed to ".listentome". Instead of checking every element for the "listentome" class, it checks only the divs, in this example.
@SeanKendle - That's not how .on() works. You can (optionally) use it to create delegated handlers, but either way it doesn't "scrape the page", it binds a listener to the specific element(s) in the jQuery object you call it on.
u
user5636597

I found the best solution for this problem by using ON with $(document).

 $(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people


Ah thanks, the above didn't work for me, but this did! (probably some weird interaction with angular and routing)
Just like Flink, I also solved problem with this. Thanks.. 100 upvote..
It is called delegation and is needed for dynamically inserted or moved content
S
SaidbakR

Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/

The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.

<!DOCTYPE html>
<html>
<head>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script src="https://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
  <a href="#" id="clicker" value="Click Me!" >Click Me</a>
  <script type="text/javascript">

        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();

        });


</script>

</body>
</html>

Notice: In the demo replace http with https there in the code, or use this variant Demo


+1 - Your answer explains why one needs the document.ready() function.
This is a better answer because the suggestion that the jquery script must be within a 'document.ready()' function is misleading. Yes, it's safer there, but if you set up the html element for a jquery function on the fly (such as query a table row depending on what button is clicked), it needs to be outside/after that function. I mistakenly changed the name of the target div for my pop-up overlays and then spent several frustrating hours looking for a script error. Big lesson learnt.
This is a wrong answer, cause the JS code should be in the head of the DOM and not inline. The fact that you spent several hours looking for the script error is not a JS problem, it's your problem not reading the docs properly and not knowing how to use debug tools.
@AndreyShipilov Who's said that, just look at the source of this page and go down to its bottom, you will see javascript code there.
@AndreyShipilov - do you know how to use debug tools to troubleshoot this issue? Then please share your knowledge with others instead of offending them. Try to be constructive and fair.
t
tjons

Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?


t
tjons

You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.

JS Code:

$(document).ready(function() {

    $("#clicker").click(function () {
        alert("Hello!");
        $(".hide_div").hide();    
    });
});

v
vicgilbcn

Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button. It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.


or, for example, z-index!
S
Simon Boudrias

You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.

$(function(){
    $('#clicker').click(function(){
        alert('hey');
        $('.hide_div').hide();
    });
});

M
Manikandan C

Just a quick check, if you are using client-side templating engine such as handlebars, your js will load after document.ready, hence there will be no element to bind the event to, therefore either use onclick handler or use it on the body and check for current target


so true, I am using flask/jinja and it is not working unless I use the onclick property in the HTML and refer from there to a function in my