Lyt*_*yth 3 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....
})
});
Run Code Online (Sandbox Code Playgroud)
一种解决方案是使用表...但是将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>
Run Code Online (Sandbox Code Playgroud)
$sibling = $(this).next('input');例如,在这个例子中。
一种方法是使用闭包。可以说,这将使用其当前值捕获变量$mainElement。
$('.element').each(function() {
$sibling = // find a sibling to $this.
$mainElement = $(this); // memorize $(this)
$sibling.change(function($mainElement) {
return function() {
// use $mainElement
}
}($mainElement))
});
Run Code Online (Sandbox Code Playgroud)
jsfiddle示例(请确保在编辑后模糊文本字段,否则.change()将不会触发)
| 归档时间: |
|
| 查看次数: |
20443 次 |
| 最近记录: |