简体   繁体   English

jQuery .live('click')仅绑定到页面上的第一个元素

[英]jQuery .live('click') only binding to first element on the page

I wrote a jQuery plugin that binds to 8 elements on a page, and I wanted to use .live() to bind the click action to a link in each element. 我写了一个jQuery插件,绑定到页面上的8个元素,我想使用.live()将click操作绑定到每个元素中的链接。 When you click the link it should post a form using ajax. 当您单击链接时,它应使用ajax发布表单。 The problem is that all the links for all 8 elements submit the form for the first element on the page. 问题是所有8个元素的所有链接都提交了页面上第一个元素的表单。 When I use .click() everything works correctly. 当我使用.click()时,一切正常。 I would prefer to use .live() since I will have adding more elements dynamically. 我更喜欢使用.live(),因为我会动态添加更多元素。

Here is some code similar to what I'm doing: 这是一些类似于我正在做的代码:

var $container = $(this);
var $form      = $container.find('form.some_form');
var $button    = $container.find('a.some_link');

This will only submit the form for the first element: 这只会提交第一个元素的表单:

$button
.live('click', function() {
  // some code that submits $form via ajax
});

However, this always submits the correct form: 但是,这总是提交正确的形式:

$button
.click( function() {
  // identical code that submits $form via ajax
});

Is there something about .live() that I should know? 有什么关于.live()我应该知道吗? Stumped. 难住了。

From the jQuery documentation : jQuery文档

Live events currently only work when used against a selector. 直播活动目前仅在对选择器使用时才有效。 For example, this would work: $("li a").live(...) but this would not: $("a", someElement).live(...) and neither would this: $("a").parent().live(...). 例如,这将起作用:$(“li a”)。live(...)但是这不会:$(“a”,someElement).live(...),这也不会:$(“a “).parent()。住(...)。

In your case, you're calling live() on a variable that's the result of a find() call. 在你的情况下,你在一个变量上调用live(),这是一个find()调用的结果。 That's not a selector. 那不是选择器。 You need to figure out a selector that identifies the elements you want. 您需要找出一个标识所需元素的选择器。


Edited to add: for anyone finding this later, the preferred approach now is to use the function on() for this. 编辑添加:对于后来发现此问题的任何人,现在首选的方法是使用on()函数。 The on() function does not have the same restriction -- since it operates on a jQuery object (rather than implicitly binding to the document) it can be set on a set of elements arrived at by chaining as in the original question. on()函数没有相同的限制 - 因为它在jQuery对象上操作(而不是隐式绑定到文档),它可以在链接到达的一组元素上设置,就像在原始问题中一样。

Try something like this. 尝试这样的事情。 You can't use "live" except on selectors. 除选择器外,您不能使用“live”。

$('a.some_link').live('click', function() {
    // some code that submits $form via ajax
});

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM