无法在动态创建的HTML按钮执行的JavaScript [英] Can't execute javascript on dynamically created html button

查看:313
本文介绍了无法在动态创建的HTML按钮执行的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​Im相当新的JavaScript / jQuery的,所以我需要一些帮助。
这里的问题。
我有一个页面,其中一个按钮会触发一个jquery动画,露出了日志的形式。(这只是取代了previous HTML那是在它的位置)
在登录表单我有它动态地创建一个按钮隐藏登录表单,并揭示了原始的HTML。但是,该按钮不能用。点击方法被调用,甚至onclick属性不工作!什么建议吗?

So im quite new to javascript/jquery, so i need some help. Here's the problem. I have a page, where a button triggers a jquery animation to reveal a log in form.(It just replaces the previous html that was in it's place) On the login form i have it dynamically create a button to hide the login form, and reveal the original html. But that button cannot be called by the .click method, or even the OnClick attribute does not work! Any Advice?

$(document).ready(function() {
$("#login_button").click(function() {
$("#menu").animate({height: "toggle"}, 500, function() {
$("#menu").empty();
$("#menu").append('<button id="back_button"></button>');
$("#menu").animate({height: "toggle"}, {duration: 500, queue: false});
});
});
});

然后code侦听的back_button点击:

And Then the code that listens for the "back_button" click:

$(document).ready(function() {
$("#back_button").click(function() {
$("#menu").animate({height: "toggle"}, 500, function() {
$("#menu").append(//Regular HTML);
$("#menu").animate({height: "toggle"}, {duration: 500, queue: false});
});
});
});

也可以javascript无法在元素上生成我的另一个JavaScript执行的?
任何想法将是巨大的!在此先感谢!

Can javascript not be executed on a element generated my another javascript? Any thoughts would be great! Thanks in advance!

推荐答案

更改code从你的背部BUTTOM:

Change the code for your back buttom from:

$("#back_button").click(function() {

$(document).on('click', "#back_button", function() {

在动态创建的元素,你需要使用jQuery的 。对() 功能。

When creating elements dynamically, you need to use jQuery's .on() function.

事件处理程序只能绑定到当前选定的元素;他们
  必须存在于网页上的时候你的code使得调用。对()。
  以确保元件是present并且可以选择,执行事件
  文档准备好处理程序内绑定对于那些中的元素
  页面上的HTML标记。如果新的HTML被注入到该网页,
  选择的元素和附加的事件处理程序后,新的HTML是
  放入页面

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

这篇关于无法在动态创建的HTML按钮执行的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆