¿Javascript Onclicks no funciona?

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.

Código:

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

En otra parte:

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

preguntado el 09 de enero de 11 a las 07:01

care to post some code? -

Have you loaded your jQuery file correctly? -

Are you using any other js libraries at the same time? -

I have loaded jQuery properly [I've been working in jsFiddle], and I am not using any other libraries. -

3 Respuestas

Es posible que desees echa un vistazo a jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:

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

Respondido el 17 de enero de 11 a las 17:01

Thankyou very much. :) This did just what I needed it to! - Georges Oates Larsen

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>

Respondido el 09 de enero de 11 a las 20:01

Cambia esto:

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

Para ser esto en su lugar:

var oc = 'activate();'

Respondido el 10 de enero de 11 a las 02:01

@Georges_Oates_Larsen This fix your code, but afEkenholm's approach is the neatest, "removing" the JS from the HTML - Ivan Buttinoni

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.