【问题标题】:jquery click() doesn't workjquery click() 不起作用
【发布时间】:2012-10-24 13:19:26
【问题描述】:

jQuery click() 函数有问题。

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

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

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

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

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

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

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

感谢您的帮助

【问题讨论】:

  • elem 不是一个元素,它是一个 id
  • [...] 替换为alert("hi there")。然后您将能够查看您对$('#myelem').click() 的呼叫是否有效。一旦确定是这样,然后将警报替换为对 ajax 函数的调用。

标签: jquery ajax asp.net-mvc-3


【解决方案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

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

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

【讨论】:

  • 这是一个很好的演示,但你应该使用他的选择器。
  • 感谢您的回复,我想通过调用 click 函数直接调用 ajax 函数(我用现有的 DOM 元素这样做)而不是调用 ajax 成功、错误……所以写一行而不是 50 !!
  • @user1069516 好吧,是的,在我的示例中执行alert() 的地方编写$.ajax() 代码。 :)