2

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);
                }
             );
        }
     );
4
  • You can put code in a specially formatted block by preceeding each line with 4 spaces, or highlighting it all and clicking the code icon (looks like binary 1s and 0s)
    – Andy E
    Dec 24, 2009 at 14:58
  • 1
    Your javascript syntax is all jacked up. What problem are you trying to solve? We could fix the syntax problems, but this [pseudo]code doesn't do anything anyway. Dec 24, 2009 at 15:02
  • This is why the tabs vs spaces debate is so relevant. Spaces only! Dec 24, 2009 at 15:32
  • It's not so bad when 1 tab = 4 spaces or 2 spaces in your editor. Some editors are kind enough to perform the conversion from tabs to spaces for you.
    – Andy E
    Dec 24, 2009 at 16:52

5 Answers 5

5

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);
            });
        }
);
2

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.

1

I think a lot of code is missing here.

But anyway, why won't you use jQuery power to bind events?

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

    var anotherTest = function(arg) {
        alert("another: " + arg);
    }

    $('#id').click(function() {
        var content = "Hello world";
        var anchor = $("<a href='#'>test</a>").click(function() { test(content); });
        //apply anchor to DOM
    });
});
1

I think this is what you're looking for:

$(document).ready(function() {
    var test = function(arg) {
      alert(arg);
    };
    var anotherTest = function(arg) {
      alert("we did something else:" + arg);
    };
    $('#id').click(function() {
      var content = "Hello world";
      var anchor = $("<a>test</a>").click(function(event) {
        event.stopPropagation();
        // test(content);
        anotherTest(content);
      });

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

This example shows good use of event.stopPropagation(). Setting an anchor's href to void() or # is often a mistake.

0
0

If you're using jQuery, I would recommend using its event handler functions like so:

$(document).ready(function() {
    var test = function(arg){
        alert(arg);
    }
    var anotherTest = function(arg){
        // do something;
    }
    $('#id').click( function(event){
        var content = "Hello world";
        var anchor = $("<a>test</a>");

        anchor.click(function(event){
            event.preventDefault(); // instead of javascript:void();
            test(content);
        });

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.