1

我正在尝试做的事情:

使用jQuery获取每个创建 <input>

  1. 这是我的HTML Code的受影响部分:

    <ul class="full_form_ul">
            <li class="full_form_ul_li" id="the_step_li">
    
                    <button class="button" id="test_button">+[Test]</button>
                    <button class="button" id="step_creation_button">+[Step]</button>
    
            </li> <!-- \\#the_step_li -->
    </ul> <!-- \\.full_form_ul -->     
    
  2. 这是正在工作的jQuerycode

    $("#step_creation_button").click(function(event)
    {   
            event.preventDefault();
            $('#the_step_li').append('<div class="step_div"><input type="text" class="step_input"><button class="the_sub_step_button" type="button" title="button">+[Sub]</button></div>');
    
    });
    
    $('#the_step_li').on('click', "button", function(event) 
    {
    
        event.preventDefault(); 
        $(this).parent('.step_div').append('<div class="sub_step_div"><input type="text" class="sub_step_input"></div>');
    
    });
    
  3. 不工作jQuery code

    $("#test_button").on('click', function(event) 
    {
    
        event.preventDefault();
    
        $(".step_div").each(function()
        {   
    
    
            alert($(this).next('.step_input').val());
            // ^ updated according to @Jeremy T's excellent response into...
            //alert($(this).children('.sub_step_input').val());
    
    
            $(this).children('.sub_step_div').each(function()
            {
                alert($(this).next('.sub_step_input').val());
                // same change from .next into .children here as well I would assume, though it doesn't work in this instance.  
            });
    
        }); // \\.step_div.each 
    
        //@EH_warch supplied a wonderful working solution for the initial problem as well
        //$("#the_step_li > .step_div > .step_input").each(function()
        //{
            //alert($(this).val());
        //})
    
    }); // \\#test_button.on('click')
    

相关(但不同)的问题:

4

3 回答 3

2

一切看起来都不错,除了你的选择器$(this).next('.step_input')

如果你想在里面找到输入this,那么你需要使用$(this).children('.step_input')

工作 jsFiddle:http: //jsfiddle.net/rKnDF/

于 2012-07-13T20:43:13.950 回答
0

抱歉,我对您的标题感到困惑,我认为这与新添加的元素无关。

你可以替换这个

$(".step_div").each(function()
{   
    alert($(this).next('.step_input').val());
}); 

为了

$("#the_step_li > .step_div > .step_input").each(function(){
    alert($(this).val());
})

更新

根据您的新请求,您可以做的最好的事情是为display您希望显示的元素添加一个类,您可以获得该元素的类来执行任何业务登录。

$("#the_step_li .display").each(function(){
    alert($(this).val() + 'and my class is: ' + $(this).attr('class'));
})

例子

于 2012-07-13T20:34:27.127 回答
0

元素仅绑定在文档准备就绪后,然后创建新元素。您需要使用 .live() 或 .delegate() 之类的东西将事件附加到动态创建的对象上。

这是关于差异的非常好的解释。

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

于 2012-07-13T20:35:57.283 回答