0

我对 jQuery click() 函数有疑问。

我使用此函数以编程方式单击一个链接,该链接调用一个将新对象添加到数据库的 ajax 函数。

当我提交表单时,在对象数据表中为我的新对象添加了一个带有新链接的 tr,我想以编程方式单击这个新链接来加载对象属性并显示它们。

问题是带有 td 和 link 的新 tr 在 DOM 中不存在并且该函数$.('#elem').click')不起作用。

我在其他帖子中看到我必须将点击事件与新的 .on 函数绑定,如下所示:

$('#parent-items').on('click', 'elem', function() {
   // [...]
});

我不知道我必须写什么来代替 [...],在我的 javascript 代码的末尾,我这样调用 click 函数:

$('#myelem').click();

谢谢你的帮助

4

1 回答 1

1

其实没那么难。:)

<table id="list">
    <tr>
        <td>John</td>
        <td><a class="btn-hi">Say Hi!</a></td>
        <td><a class="btn-bye">Say Goodbye!</a></td>
    </tr>
    <tr>
        <td>Lucy</td>
        <td><a class="btn-hi">Say Hi!</a></td>
        <td><a class="btn-bye">Say Goodbye!</a></td>
    </tr>
    <tr>
        <td>Sam</td>
        <td><a class="btn-hi">Say Hi!</a></td>
        <td><a class="btn-bye">Say Goodbye!</a></td>
    </tr>
</table>

<script>
$('#list').on('click', 'a', function() {
    // Wrap the clicked <a> element with jQuery
    var $this = $(this);

    // Get the parent <tr> element
    var $tr = $this.closest('tr');

    // Get all (direct) children elements (<td>) that are inside the current <tr> element
    var $tds = $tr.children();

    // Get the text from the first <td> element in the current row
    var name = $tds.eq(0).text();

    // Get the type (class name) of clicked link
    var type = $this.attr('class');

    if (type == 'btn-hi') {
            alert( 'Hi, ' + name + '!' );
    } else if (type == 'btn-bye') {
            alert( 'Goodbye, ' + name + '!' );
    }
});
</script>

看看 JSBin 中的这个演示:http: //jsbin.com/welcome/38776/edit

每次用户单击<a>元素内部的任何元素时,都会执行单击事件<table id="list">。它被称为“事件委托” - http://api.jquery.com/delegate/

因此,您可以动态地向表中添加更多行,一切仍然有效。

于 2012-10-24T13:22:55.543 回答