简体   繁体   中英

jQuery click(function() not working but plain Javascript working just fine

THIS IS THE FULL SCRIPT

http://goo.gl/HoCxk

I have a problem with this function:

    $('.message').click(function(){
    alert("it works");
    var clicked_msg=$(this);
    $('#current_message').html(clicked_msg.attr("id"));
});

If instead of the above I add an onclick="msgClicked()", and then do something like this:

function msgClicked(){
var x=document.getElementById("current_message");alert("it works");x.innerHTML("test");}

The jQuery library is obviously imported as literally everything else is done using the jQuery framework and all the other functions implemented on the messaging system are jQuery. Everything works perfect there but for some reason I can't figure out what is wrong with this one.

If any of you are willing to help out and you need to see what is actually going on, please let me know and I will create an account for you on my website. Removing all the protection from the content would take a looong long time.

How are you?

Usually these little annoyances are caused because:

  • You made a typo (such as .message being incorrectly spelled in either JS or the HTML)
  • You are trying to assign this function to an element which has not been yet created

Just to be sure, try this:

alert($('.message').length)
$('.message').click(function(){
    alert("it works");
    var clicked_msg=$(this);
    $('#current_message').html(clicked_msg.attr("id"));
});

If it outputs 0, it's because one of the two problems above might be happening, and then, try this:

$(function(){
    alert('The page loaded!');
    alert('.message elements in page: ' + $('.message').length);
    $('.message').click(function(){
        alert("it works");
        var clicked_msg=$(this);
        $('#current_message').html(clicked_msg.attr("id"));
    });
});

If you don't get any alert messages, there's something wrong with your jQuery import, and it might be a conflict (such as including jQuery twice!)

If the .message elements in page are more than 0, then it was the second issue (you were trying to assign the .click event to an element which hadn't been yet created)

And if it still says 0 elements, then there are no elements with class "message" created.

I hope this points you in the right direction.

Cheers!

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