Georges Oates Larsen
Georges Oates Larsen

Reputation: 7092

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.

For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".

I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.

Code:

function button(votefor)
{
    var oc = 'function(){activate();}'
    return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}

Elsewhere in code:

var buttons = '';
    for (var i = 2; i < strs.length; i++)
    {
        buttons += button(strs[i]);
    }
    var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);

Elsewhere:

function activate()
{
    alert("Testing");
}

Upvotes: 0

Views: 157

Answers (3)

Alexander Wallin
Alexander Wallin

Reputation: 1394

You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:

$(".somebtn").live("click", myClickHandler);

Upvotes: 2

Shadow Wizard
Shadow Wizard

Reputation: 66389

Change this:

var oc = 'function(){activate();}'

To be this instead:

var oc = 'activate();'

Upvotes: 0

Ivan Buttinoni
Ivan Buttinoni

Reputation: 4145

Follows a dummy example, may be this can help you.

<!DOCTYPE html>
<html>
<head>
<style>

</style>

<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">

$(function() {

        $('.go-right').click(function(){

                c="Hello world";
                $("#output").html(c);
        });

});

</script>

</head>
<body >


<div id="output"></div>

<a class="go-right">RIGHT</a>

</body>
</html>

Upvotes: 1

Related Questions