Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript jQuery binding

I am using jQuery to create an anchor and bind it with JavaScript function as follow:

  $(document).ready
    (
        function()
        {
                var test = function(arg)
                           {
                              alert(arg);
                           }
                var anotherTest = function(arg)
                                  {
                                         do something;
                                   }
                $('#id').click
                (
                    var content = "Hello world";
                    var anchor = "<a href='javascript:void(0);' onclick='test(\"" + content + "\")' >test</a>";

                     $('#DivToBind').prepend(anchor);
                );
            }
    );

And the problem is: the test function always alerts "a", no matter what the value of content is. If I change onclick function test to anotherTest, nothing happens but "anotherTest is not defined" appeared in the error console

Edit

To better identify my problem, I summarise my real code as follow

   $(document).ready
    (
        function()
        {

                  var deleteComment = function (comment)
                    {
                          commentInfo       = comment.split('_');
                         var postid         = commentInfo[0];
                        var enum        = commentInfo[1];
                        var parentid    = commentInfo[2];
                        var user        = commentInfo[3];
                        var author      = commentInfo[4];
                        var date        = commentInfo[5];

                        $.get
                        (
                            "ajaxhandle.php",
                            {ref: 'commentdelete', pid: postid,  d: date},
                            function(text)
                            {
                                if (text)
                                {
                                    //alert(comment);
                                    $('#' + comment).html('');
                                }
                                else
                                {
                                    alert("Something goes wrong");
                                }
                            },
                            'text'
                         );
                    };
            var test = function(arg) {alert(arg);};

            $('#postCommentButton').click
            (
                function ($e)
                {
                    $e.preventDefault();
                    var comment = $('#postdata').val();
                    var data = $('form#commentContent').serialize();
                    //alert(data);
                    $.post
                    (
                        "ajaxhandle.php",
                        data,
                        function($xml)
                        {
                            $xml = $($xml);
                            if ($xml)
                            {

                                //alert(45);
                                var success         = $xml.find("success").text();
                                if (success == 1)
                                {
                                    $('#postdata').val("");
                                    var id              = $xml.find("id").text();
                                    var reference       = $xml.find("reference").text();
                                    var parentid        = $xml.find("parentid").text();
                                    var user            = $xml.find("user").text();
                                    var content         = $xml.find("content").text();
                                    var authorID        = $xml.find("authorid").text();
                                    var authorName      = $xml.find("authorname").text();
                                    var converteddate   = $xml.find("converteddate").text();
                                    var date            = $xml.find("date").text();
                                    var avatar          = $xml.find("avatar").text();

                                    comment = id + '\_wall\_' + parentid + '\_' + user + '\_' + authorID + '\_' + date;

                                    //alert(comment);
                                    var class = $('#wallComments').children().attr('class');
                                    var html = "<div class='comment' id='" + comment +  "' ><div class='postAvatar'><a href='profile.php?id=" + authorID + "'><img src='photos/60x60/" + avatar +"' /></a></div><div class='postBody' ><div class='postContent'><a href='profile.php?id=" + authorID + "'>" + authorName + " </a>&nbsp;<span>" + content + "</span><br /><div class='timeline'>Posted " + converteddate + "<br /><a href=''>Comment</a> &nbsp; | &nbsp; <a href=''>Like</a>&nbsp; | &nbsp; <a href='javascript:void(0);' onclick='deleteComment(\"" + comment + "\")' class='commentDelete' >Delete</a></div></div></div><div style='clear:both'></div><hr class='hrBlur' /></div>";

                                    if (class == 'noComment')
                                    {
                                        //alert($('#wallComments').children().text());
                                        //alert(comment);
                                        $('#noComment').html('');
                                        $('#wallComments').prepend(html);
                                    }
                                    else if(class = 'comment')
                                    {
                                        //alert(comment);

                                        $('#wallComments').prepend(html);
                                    }
                                }
                                else
                                {
                                    alert("Something goes wrong");
                                }   
                            }
                            else
                                alert("Something goes wrong");
                        },
                        'xml'
                     );


                }
             );



            $(".comment").find('.commentDelete').click
            (
                function($e)
                {
                    $e.preventDefault();
                    var comment     = $(this).parent().parent().parent().parent().attr('id');
                    deleteComment(comment);
                }
             );
        }
     );
like image 259
Kabuky Avatar asked Nov 22 '25 08:11

Kabuky


2 Answers

var test=... is inside a function, it's not going to be in scope on the page when you want to call it onclick the anchor.

to make it global you can leave off the var.

you could also do something like:

$(document).ready
(
    function()
    {
            var test = function(arg)
                       {
                          alert(arg);
                       }
            var anotherTest = function(arg)
                              {
                                //do something;
                              }
            $('#id').click
            (
                function(){
                var content = "Hello world";
                var anchor = "<a href='javascript:void(0);'>test</a>";
                $(anchor).click(function(){ test(content); });
                $('#DivToBind').prepend(anchor);
            });
        }
);
like image 157
John Boker Avatar answered Nov 23 '25 22:11

John Boker


Your example is incomplete. The call to bind click is missing a function wrapper (so it's a syntax error and won't even parse); there is no reference to calling anotherText;, and the anchor is never actually created, only a string. So it's not really possible to fix from there.

In general avoid creating dynamic content from HTML strings. As you are not HTML-escaping content, if it contains various special characters (<"'&) your script will fail and you may have a cross-site-scripting security hole. Instead, create the anchor and then write any dynamic attributes or event handlers from script:

$(document).ready(function() {
    function test(arg) {
        alert(arg);
    }

    $('#id').click(function() {
        var content= 'Hello world';
        $('<a href="#">test</a>').click(function(event) {
            test(content);
            event.preventDefault();
        }).appendTo('#somewhere');
    });
});

It may be preferable to use a <button> styled like a link rather than a real link, since it doesn't go anywhere. A <span> styled as a link is another possibility, preferably with a tabindex attribute to make it keyboard-accessible in that case.

like image 27
bobince Avatar answered Nov 23 '25 20:11

bobince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!