繁体   English   中英

jQuery使用另一个js脚本访问附加的元素ID

[英]Jquery accessing appended element id with another js script

我试图在我使用JQUERY附加到页面的HTML元素上调用js函数。

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

我的jQuery在js函数中。

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

因此,第三部分是使用答案和js,然后重新加载花药字段。 然后加载另一个功能->新的答案字段。

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

因此,当我尝试调用js函数时,例如answer_one()/ answer_two(),该函数无法从输入ID的--->中获取变量,我认为它们是因为加载页面时未加载元素!

有没有针对此的jQuery / js解决方法?有什么想法吗?

是否可以解决类似这样的问题?

我认为将HTML附加在一行中是一个好习惯,例如:

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

没有时间测试任何东西,但是用于访问插入的代码的jQuery解决方法是.live()

为什么要使用jQuery但不使用$() / jQuery()选择器来选择元素?

尝试注释掉//$('ul#id').remove()行和dupm $('ul#id').size()进行控制台操作,以便知道您的元素存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM