Jquery not working in dynamically generated form

送分小仙女□ 提交于 2019-12-11 14:59:15

问题


I am generating a form in www.sitetwo.com by using some scripts called from www.siteone.com. As I have to submit the form in www.sitetwo.com to www.siteone.com, I am using Ajax using JSONP method. But, the generated form is not supporting any scripts. My code is here:

   //script in www.sitetwo.com
    <script type="text/javascript">
    window.onload = function () {
        "use strict";
        function js(n) {
            var s = document.createElement('script');
            s.setAttribute("type", "text/javascript");
            s.setAttribute("src", n);
            document.getElementsByTagName("head")[0].appendChild(s);
        }
        js("http://www.siteone.com/script.js");
    };
    $(document).ready(function(){
    $=jQuery.noConflict();
    $(".submitbutton").hover(function(){
      alert("hai");
    }
    </script>
    <div id="newform">
    </div>

The form that is dynamically rendered in div with id newform is as follows:

<form>
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="go" class="submitbutton">
</form>

I tried applying basic script of on hover alert.But it isn't working. cannot we use directly scripts like this for dynamically generated forms. If so how can we overcome this problem. I have searched for errors in browser. No error is shown. What can be the solution??


回答1:


$(".submitbutton").hover(function(){
      alert("hai");
    }

change in

$(".submitbutton").on("hover",function(){
      alert("hai");
    }

reference hover




回答2:


You are generating the form dynamically, to apply some events to the dynamic element you have to use .on(), other thing is to change the event to mouseenter or mouseleave instead of hover

try this:

$(document).on('mouseenter', '.submitbutton', function(){
  alert("hai");
}



回答3:


You can't use hover in that case, need to use delegated event handlers using events mouseenter and mouseleave

.hover() is not a event, it is a helper method to register mouseenter and mouseleave event handlers

Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

$(document).on('mouseenter', '.submitbutton', function(){
  alert("hai");
}


来源:https://stackoverflow.com/questions/18380864/jquery-not-working-in-dynamically-generated-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!