jquery - 每个() jQuery 中的 Change()

标签 jquery event-handling

处理这种情况的最佳方法是什么:

$('.element').each(function() {

    $sibling = // find a sibling to $this.
    $mainElement = $(this); // memorize $(this)
    $sibling.change(function() {
       // when sibling changes
       // do something using $mainElement
       // problem is, $mainElement is not the element you think
       // $mainElement is the last .element found....
    })
});

一个解决方案是一个表...但是将change()嵌套在each()中没有任何优势...

我的 html 示例:

<div id="first">
  <span class="element"></span>
  <input name="first" type="text" />
</div>
<div id="second">
  <span class="element"></span>
  <input name="second" type="text" />
</div>

在此示例中,例如 $sibling = $(this).next('input');

最佳答案

一种方法是使用 closure 。这将捕获 $mainElement 中的变量,可以说,使用其当前值。

$('.element').each(function() {

    $sibling = // find a sibling to $this.
    $mainElement = $(this); // memorize $(this)
    $sibling.change(function($mainElement) {
        return function() {
            // use $mainElement
        }
    }($mainElement))
});

jsfiddle example (编辑后请务必模糊文本字段,否则 .change() 将不会触发)

关于jquery - 每个() jQuery 中的 Change(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14910100/

相关文章:

javascript - 如何删除 d3.behavior.drag().on ("drag",...) 事件处理程序

excel - 在 Excel 中捕获工作表取消保护事件

javascript - 数据表。如何阻止从事件处理程序内部触发 search.dt 事件

javascript - 普通 JavaScript 版本的 jQuery .click

jquery - jQuery : ajaxError always fires last

javascript - jquery 没有功能?

javascript - 单击 PHP 后禁用按钮

javascript - 滚动页面后的 jQuery slideUp 错误

jquery - 无法解析来自 jquery Ajax 调用的 JSON 响应

c# - 按下WPF/MVVM右上角的关闭图标时如何处理关闭窗口?