Monday, December 1, 2008

[jQuery] Re: Can jQuery genrated tag to trigger handler?

It's a scope problem. When javascript parses that $("#goto").click(...) line, #goto does not yet exist. You need to assign the click handler to #goto within the same function that creates the link.

Try this:

function pageReady()
{
    $("#go").click(function()
    {
        $("div#content").append('<a href="#" id="goto">Generated Click</a>');
        $("#goto").click(function() { alert("hello from genrated click!"); });
    });
};

On Mon, Dec 1, 2008 at 4:37 AM, harry <hyharrysun@gmail.com> wrote:

Hi, all,

I simply create a button to generate a hyperlick(or button) in html,
can the generated link or button to call controller in mvc? here just
simple code to illustrate my question:

 <script type="text/javascript">
       $(pageReady);
       function pageReady() {

           var tag = "<a href='#' id='goto'>Generated Clilk</a>";
           $("#go").click(function() { $("div#content").append
(tag); });
           $("a#goto").click(function() { alert("hello from genrated
click!"); });
       };

   </script>

</head>
<body>
   <div>
       <button id="go">
           Click ME</button>
   </div>
   <div id="content" />
</body>

The problem is the  $("a#goto") never get fired. Is it possible to do
so?
Thanks.

Harry

No comments: