javascript或jQuery在动态生成的内容中不起作用 [英] javascript or jQuery doesn't work in dynamically generated content
问题描述
基本上,我创建了基于用户点击导航菜单的内容生成内容的网页。
我面临的问题:
- 当主页面从内容页面生成内容时, jquery或javascript无效。
- 但当我单独打开内容页面时,一切正常。
通过搜索收集的信息:
jQuery.load()方法忽略与该内容一起提供的脚本标记动态生成。
所以我尝试以下方法:
- 将我需要的标签放在主页面中,而不是放在内容页面中。它不起作用。好像jquery找不到内容元素,因为它们是动态生成的。
- 由于jQuery.load()忽略了脚本标记,我尝试了纯粹的javascript ajax,就像w3schools.com如何教,xmlhttp方式,生成内容。它不起作用。
- 单击按钮时。在控制台中没有响应。
示例 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'>名字< / label>< br />
< input id =fnametype =textname =fnamemaxlength =100/>
< / form>
< div id =theresult>< / div>
当此contact.php动态生成到其他页面时,它不起作用。当我单击提交按钮时,控制台显示无响应。似乎jquery不存在。
但是当我在浏览器中单独打开它时,它可以工作。
对于动态生成的元素,您应该委派事件,您可以使用 on
方法:
$(function(){
$(document).on('click','#submitUser',function(e){
var fname = $(#fname ).val();
$(#theresult)。text(fname);
e.preventDefault();
});
});
live()
方法已弃用。
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:
- when main page generate contents from content-page, jquery or javascript won't work.
- 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:
- 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.
- 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.
- 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.
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.
这篇关于javascript或jQuery在动态生成的内容中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!