php - javascript 或 jQuery 不适用于动态生成的内容

标签 php javascript jquery dynamic-content

人们早安。如何让我的 javascript 或 jquery 在动态生成的内容中工作。

基本上,我已经创建了根据用户在导航菜单上单击的内容生成内容的网页。

我面临的问题:

  1. 当主页面从内容页面生成内容时,jquery 或 javascript 将不起作用。
  2. 但是当我单独打开内容页面时,一切正常。

通过搜索收集的信息:

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

所以我尝试以下操作:

  1. 将我需要的标签放在主页面,而不是内容页面。它不起作用。 jquery 似乎找不到内容元素,因为它们是动态生成的。
  2. 由于 jQuery.load() 忽略脚本标记,我尝试了纯 javascript ajax,就像 w3schools.com 教授的那样,即 xmlhttp 方式,以生成内容。它不起作用。
  3. 单击按钮时。控制台无响应。

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

当这个contact.php动态生成到其他页面时,它不起作用。当我单击“提交”按钮时,控制台没有显示任何响应。好像 jquery 不存在。
但是当我在浏览器中单独打开它时,它起作用了。

最佳答案

对于动态生成的元素,你应该委托(delegate)事件,你可以使用on方法:

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

live() 方法是 deprecated .

关于php - javascript 或 jQuery 不适用于动态生成的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12022027/

相关文章:

php - 遍历json数组并插入mysql php

javascript - 如果线的原点不在相机的 View 中,则使用 BufferGeometry 绘制的 THREE.js 线不会呈现

javascript - ScrollReveal() 有一些问题

javascript - Chart.js 图表从未生成

css - 在 IE8 中使用 jquery 加载 css 的问题

javascript - 使用 php 从 MySQL 表中选择并显示

php - Laravel 同步不适用于空数组

php - 使用 rds 数据库实例在 aws elastic beanstalk 中托管 laravel 应用程序

javascript - Php, Jquery/JS, 提交按钮

php - 如果 mysql 中存在记录,如何构建 php 代码以填充表单中的 280 个字段