事件不触发动态创建的元素(JQuery) [英] Events not firing on dynamically created elements (JQuery)

查看:122
本文介绍了事件不触发动态创建的元素(JQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个页面,需要用户能够创建输入元素,我需要能够从这些元素检索基于事件的数据。

I'm creating a page that requires a user to be able to create input elements, and I need to be able to retrieve the data from those elements based on events tied to them. I am appending them to the body of the document, and they are appending properly, but then their events aren't firing.

JSFiddle:我们将文档添加到文档的正文中, http://jsfiddle.net/g7Sdm/2/

JSFiddle: http://jsfiddle.net/g7Sdm/2/

基本HTML

<input type="radio" class="userInput" value="I'm a radio button that already existed when the page loaded." />Pre-Existing Radio Button
<input type="text" class="userInput userTextInput" value="Text" />
<button type="button" id="addRadio">Add Radio Button</button>
<button type="button" id="addText">Add Text Input</button>

Javascript

$(document).ready(function() {
    $("#addRadio").click(function() {
           $("html").append("<input type=\"radio\" class=\"userInput\" value=\"I'm a dynamically added radio button!\" />New Radio Button<br />");
    });
    $("#addText").click(function() {
           $("html").append("<input type=\"text\" class=\"userInput userTextInput\" value=\"Text\" /><br />");

    });
    $(".userInput").click(function() {
        alert($(this).val()); 
    });
    $(".userTextInput").keyup(function() {
        alert($(this).val()); 
    });
});

感谢任何帮助!

推荐答案

你必须使用 on()方法,因为元素必须被dinamically绑定

You have to use the on() method, as the elements have to be binded dinamically

$(document).ready(function() {
    $("#addRadio").click(function() {
           $("html").append("<input type=\"radio\" class=\"userInput\" value=\"I'm a dynamically added radio button!\" />New Radio Button<br />");
    });
    $("#addText").click(function() {
           $("html").append("<input type=\"text\" class=\"userInput userTextInput\" value=\"Text\" /><br />");

    });
    $(document).on("click","userInput",function() {
        alert($(this).val()); 
    });
    $(document).on("click",".userTextInput",function() {    
        alert($(this).val()); 
    });
});

这是 demo

这篇关于事件不触发动态创建的元素(JQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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