0

The script below adds items to an array when you click the link, and generates a list of items as html output. You can see an example here: http://jsfiddle.net/dqFpr/

I am trying to create a function to delete items from the list. Not a difficult task with splice(), but somehow clicking the delete link doesn't trigger the test_function() function.

Can someone tell me what I am doing wrong, or show me another way of triggering the function? Your help is really appreciated ;-)

<script language="javascript">
    $(document).ready(function() {
        function test_function( number ) {
            /* This function is not triggered, nothing works inside here!! */
        }
    });

    var lines = [];
    function update_list( lines ) {
        var thecode = '';
        for(var i = 0; i < lines.length; i++) {
            thecode = thecode + lines[i] + ' <a onclick="javascript:test_function('+i+')" href="#">(delete)</a><br />';
        }
        $('div#display').html(thecode);
    }

    $('a#new').click(function() {
        lines.push('another line');
        update_list(lines); 
    });
</script>

<div id="display"></div>
<a href="#" id="new">Add a new line</a>
2
  • 1
    Please refer to this post: stackoverflow.com/questions/203198/… Commented Jul 19, 2011 at 5:38
  • @Satjinder Singh Bath - this is a function scope issue, not a listener binding issue. Commented Jul 19, 2011 at 5:56

1 Answer 1

1

Because in the text assigned to display's innerHTML, *test_function* is just plain text that is evaluated by the HTML parser. At that point, its scope is global, not within the IIFE passed to $(document).ready(). You can fix that by making the function global:

$(document).ready(function(){

    window.test_function = function (number) { 
      // do stuff
    }
    ....
});

or

var test_function;
$(document).ready(function(){

    test_function = function (number) { 
      // do stuff
    }
    ....
});

Or whatever method you like to get access to the function. But while it is declared inside an anonymous function's scope, you can only get access to it from a function that has a closure to the variables in that scope.

Sign up to request clarification or add additional context in comments.

1 Comment

That solves it. Thank you very much for your effort! Really appreciated ;-)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.