【发布时间】:2019-04-03 17:11:59
【问题描述】:
$( document ).ready(function() {
var feature = (function() {
var items = $( "#myFeature li" );
var showItem = function() {
currentItem = $( this );
// more code goes here;
};
var showItemByIndex = function( idx ) {
$.proxy( showItem, items.get( idx ) );
};
items.click( showItem );
return {
showItemByIndex: showItemByIndex
};
})();
feature.showItemByIndex( 0 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myFeature">
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
</div>
上面的代码 sn-p 来自这里的 jQuery 文档https://learn.jquery.com/code-organization/concepts/
公共函数feature.showItemByIndex(0) 没有执行,有人能解释一下吗?
【问题讨论】:
-
欢迎来到stackoverflow!我认为如果您包含示例中的 HTML 将会很有帮助,这样我们就可以了解它为什么不起作用。
-
@John 添加了示例 html 以供参考。
-
您能否详细说明“未执行”?
-
例如,如果我调用
feature.showItemByIndex(1)来选择列表中的第二个元素并执行自定义函数,则它不起作用。它在没有 $.proxy(...) 的情况下工作 -
@asedsami 是的,我已经放置了一个断点和 console.log,它绝对不会在页面加载时执行功能。但适用于项目点击事件。
标签: javascript jquery modular