1

ユーザーが入力要素を作成できるようにする必要があるページを作成しています。これらの要素に関連付けられたイベントに基づいて、それらの要素からデータを取得できる必要があります。それらをドキュメントの本文に追加していますが、適切に追加されていますが、イベントが発生していません。

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()); 
    });
});

助けてくれてありがとう!! とても遅く、眠る必要がありますが、朝にまたチェックします。

4

2 に答える 2

3

on()要素を動的にバインドする必要があるため、メソッドを使用する必要があります

$(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()); 
    });
});

ここにデモがあります

于 2013-06-15T06:30:30.257 に答える
2

への変更:

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

$(document).on("click", ".userTextInput", function() {
    alert($(this).val()); 
});
于 2013-06-15T06:27:32.757 に答える