javascript or jQuery doesn't work in dynamically generated content

一世执手 提交于 2019-11-27 04:43:41

问题


Morning people. How to make my javascript or jquery works in dynamically generated content.

Basically, i have created web page that generates contents, base on what user clicks on the navigation menu.

The problems i am facing:

  1. when main page generate contents from content-page, jquery or javascript won't work.
  2. but when i open up the content-page alone, everything works.

Information collected through searching:

jQuery.load() method ignores the script tag that comes together with the that content generated dynamically.

So i try the following:

  1. Put the tag that i need in main page, not in content-page. it doesn't work. seem like the jquery can't find the content element, because they are dynamically generated.
  2. Since jQuery.load() ignores script tag, I tried pure javascript ajax like how w3schools.com teaches, the xmlhttp way, to generate the content. It doesn't work.
  3. When a button is clicked. no response in console.

Example contact.php

<script type="text/javascript">
$(function() {
    $("#submitUser").click(function(e) {
    var fname = $("#fname").val();
    $("#theresult").text(fname);
    e.preventDefault();
});
});
<form id="contactForm"> 
<label for='fname' >First Name</label><br/>
<input id="fname" type="text" name="fname" maxlength="100" />
</form>
<div id="theresult"></div>

When this contact.php is dynamically generated into other page, it doesn't work. When I click "submit" button, console shows no response. seem like the jquery is not exists.
But when I open it alone in browser, it works.


回答1:


For dynamically generated elements you should delegate the events, you can use the on method:

$(function() {
    $(document).on('click', '#submitUser', function(e) {
       var fname = $("#fname").val();
       $("#theresult").text(fname);
       e.preventDefault();
    });
});

live() method is deprecated.




回答2:


Taking a wild stab in the dark here since your question isn't very well-described, but perhaps you're trying to use .click() and so on to bind events to things that are getting dynamically loaded into the page?

If so, you probably want to look at .on() instead.




回答3:


You need to use live event.

As an example, if your generated content contain a click event, you could do this:

$(".something").live("click", function({ 
// do something
)};



回答4:


For dynamically generated fields use .on() JQuery method:

$(document).on('click', '#MyID', function(e) {
    e.preventDefault(); // or you can use "return false;"
});


来源:https://stackoverflow.com/questions/12022027/javascript-or-jquery-doesnt-work-in-dynamically-generated-content

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