如何将.editable()应用于动态添加的元素

时间:2013-03-28 19:44:49

标签: javascript jquery

我有一个在$(document).ready()上执行此javascript的网页。 .editable()来自X-Editable javascript library(就地编辑)。

$('tr td:nth-child(2) a').editable();

我页面上的链接/按钮允许向表中添加行。有没有办法在new上执行editable()而不是像以前一样使用相同的选择器并让它再次获取所有匹配项?

$('#newCriteria').click(function () {
    var id = 0;

    // load template
    var cTemplate = $('#criteriaTemplate').html();

    // fill template
    var template = cTemplate.format(id, 'New Field');

    // attach editable (doesnt work)
    $('tr td:nth-child(2) a', template).editable();

    // append to table
    $('#criteriaTable').append(template);
});

正如你所看到的,我以为我会尝试将模板html作为上下文传递给jQuery,但由于它实际上不是DOM的一部分,所以在我追加它之前,它不起作用。

另一种可能的解决方案是我可以将选择器修改为'tr:last-child td:nth-child(2) a'

我想知道是否有一些为什么要在元素上使用.on()让jQuery自动为我添加处理程序。我过去只使用.on()来添加像.on('click', '...', function() {})这样的处理程序,我不知道它是否可以用于editable()之类的东西。

模板:

<script type="text/template" id="criteriaTemplate">
        <tr data-criteriaID='{0}'>
            <td><i class="icon-remove" /></td>
            <td><a href="#">{1}</a></td>
            <td><a href="#" data-value="0">String</a></td>
        </tr>
    </script>

1 个答案:

答案 0 :(得分:2)

x-editable具有selector选项,因此您可以将.editable应用于表格标记:

$('#table').editable({
  ...
  selector: 'tr td:nth-child(2) a'
});
相关问题