简体   繁体   中英

Console not logging after onClick event

I have HTML div that resemble a star rating system.

I'm trying to simple test some javascript so that when I click a star then the console logs 'hello'.

<div class=rating>
    <div class="ratings_stars" data-rating="1"></div>
    <div class="ratings_stars" data-rating="2"></div>
    <div class="ratings_stars" data-rating="3"></div>
    <div class="ratings_stars" data-rating="4"></div>
    <div class="ratings_stars" data-rating="5"></div> 
</div>

$('.ratings_stars').on('click', function() {
    console.log('Hello');
});

The JS is in a separate file and I've linked that fine.

Your class needs to be in quotes, and place your jQuery listeners in a document ready function:

 $(document).ready(function() { $('.ratings_stars').on('click', function() { console.log('Hello'); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="rating"> <div class="ratings_stars" data-rating="1">Click me</div> <div class="ratings_stars" data-rating="2">Click me</div> <div class="ratings_stars" data-rating="3">Click me</div> <div class="ratings_stars" data-rating="4">Click me</div> <div class="ratings_stars" data-rating="5">Click me</div> </div>

All sorted.

Needed to wrap in a DOMReady Event.

Thanks for the help everyone.

$(function () {
$('.ratings_stars').on('click', function() {
    console.log('Hello');
});
});

Use MichaelvE answer for the code. I want to add the following, in your code:

$(document).ready(function() {
  $('.ratings_stars').on('click', function() {
    console.log('Hello');
  });
});

The $(document).ready(function() {/* code to be executed */}); part is necesarry for the DOM to build up. The DOM is an in memory tree like representation of an HTML file which we can alter programmatically via JS/JQuery. What JQuery does under the hood is adding an event listener to all all DOM elements which contain the rating_stars class.

The JS engine can execute code before the DOM is built up. This will lead to an error because JQuery tries to attach an event handler to a non existing DOM element.

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