开发者

Jquery accessing appended element id with another js script

Im trying to call a js function on a HTML element which I have appended to the page using JQUERY.

   <body>
        <div id='father'>

        </div>
<input type="submit" value="choice one" onclick='choice_one()'/>    
<input type="submit" value="choice two" onclick='choice_two()'/>    
<input type="submit" value="choice three" onclick='choice_three()'/>    
   </body>

My jQuery is in a js function..

   <script>
         function choice_one(){

         var container = "<div id='field'>
                <form>
              <input type="text" id='choice_one_answer' value="" /> 
              <input type="submit" value="submit" onclick='answer_one()'/>  
                </form>
                         </div>";

         $('ul#field').remove();
         $("div#father").append(container);

        }

         function choice_two(){

         var container = "<div id='field'>
                <form>
              <input type="text" id='choice_two_answer1' value="" />    
              <input type="text" id='choice_two_answer3' value="" />    
              <input type="submit" value="submit" onclick='answer_two()'/>  
                </form>
                         </div>";

         $('ul#field').remove();
         $("div#father").append(container);

        }

   </script>

So the third part is using the answers and with js then reloading anther field. T开发者_Python百科hen loading another function --> new answer field.

   <script>
          function answer_one(){

             var answer = document.getElementById('choice_one_answer');

             do something with answer...

           choice_two();

           }

          function answer_two(){

             var answer_one = document.getElementById('choice_two_answer1');

             var answer_two = document.getElementById('choice_two_answer2');


             do something with answer...

          choice_one();

           }

           other functions....

   </script>

So when I try to call the js functions eg answer_one()/ answer_two() the function cannot grab the variable from the input Id's ---> i presume their is because the element were not loaded when the page loaded!

Is there a jQuery/ js workaround for this... any thoughts??

Is there a work around for something like this??


I think it's a good practice to append html in one line, like this:

var container = "<div id='field'><form><input type="text" id='choice_one_answer' value="" /><input type="submit" value="submit" onclick='answer_one()'/></form></div>";

Don't have the time to test anything, but the jQuery workaround for accessing inserted code is .live()


Why are you using jQuery but not using $()/jQuery() selector for selecting the element?

Try to comment out the //$('ul#id').remove() line and dupm $('ul#id').size() to console in order to know that your element exists.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜