【问题标题】:jquery next() on element that was just addedjquery next() 在刚刚添加的元素上
【发布时间】:2012-11-06 23:35:29
【问题描述】:

这就是我想要发生的事情:

  • 有人在输入字段中输入文本
  • 当他们在键盘上点击 ENTER 时,它会使用 after() 函数在当前输入字段之后添加一个输入字段,然后聚焦该输入字段,以便他们可以继续输入并一遍又一遍地执行此操作

这是我的代码不起作用:

$('.table-todo input[type=text]').live('keypress', function (e) {   
    if (e.which == 13) 
    {
        $parent = $(this).parent('.field');     
        $.get('projects-add-task.php?show_delete=yes', function (data) { $parent.after(data); }, 'html');
        $(this).next('input[type=text]').focus();
    }
});

这是projects-add-task.php的内容:

<div class="field">
<input type="text" name="task[]" />
<a href="#" title="Add Task Below" class="todo-add"><img src="images/icon-todo-add.png" alt="" onmouseover="this.src='images/icon-todo-add-h.png'" onmouseout="this.src='images/icon-todo-add.png'" /></a>
<?php if ($_GET['show_delete'] == 'yes') { ?>
<a href="#" title="Delete This Task" class="todo-delete"><img src="images/icon-todo-delete.png" alt="" onmouseover="this.src='images/icon-todo-delete-h.png'" onmouseout="this.src='images/icon-todo-delete.png'" /></a>
<?php } else { ?>
<img src="images/icon-todo-delete-o.png" alt="" />
<?php } ?>
<div style="clear: both;"></div>
</div>

它只是没有关注通过$.get 添加的输入,我不知道如何修复它。它正在将下一个输入字段添加到页面中,但它没有聚焦它。

【问题讨论】:

  • 您能在jsfiddle.net 上重现问题并链接到它吗?如果人们可以自己运行代码,则更容易提供帮助。
  • 不应该是$(this).next('input[type=text]').focus();$parent.next('input[type=text]').focus(); 吗?

标签: php jquery next


【解决方案1】:

你可以这样做:

    $parent = $(this).parent('.field');    
    $this = $(this);
    $.get('projects-add-task.php?show_delete=yes', function (data) { 
        $parent.after(data); 
        $parent.next().children('input[type=text]').focus();
    }, 'html');

问题是在执行$(this).next('input[type=text]').focus(); 时实际上并没有创建下一个输入元素,因为您正在使用AJAX 调用来创建它。你还需要父母的下一个元素。

【讨论】:

  • 您的代码不起作用。我知道这就是问题所在,我需要在调用next() 函数之前创建新元素live,但我不知道该怎么做。
  • 已编辑。您正在检查该元素的下一个元素,但实际上它应该是父元素的下一个元素...
猜你喜欢
  • 2011-01-27
  • 2011-05-22
  • 2011-09-05
  • 2013-04-13
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多