我有这个代码,可以看到Here。我的想法是,我可以有一个项目列表,然后我可以分配一个处理程序来运行我需要运行的任何重复代码(例如,修改一系列类的函数)。我的想法是我可以遍历一个id列表并分配一个处理程序,但是由于我对Javascript的了解有限,它似乎并没有起作用。有人能帮忙吗?
感兴趣的代码:
HTML:
<a href="#" id="first">First</a><br>
<a href="#" id="second">Second</a><br>
<a href="#" id="third">Third</a><br>
<a href="#" id="forth">Forth</a><br>
使用Javascript:
//Choose which ids I want to iterate
ids = ['#first', '#second', '#third', 'forth']
//For all the ids there are
for ( i=0; i<ids.length; i++ ) {
//Select an item
item = ids[i]
//Add a click handler to that item
$( item ).click(function() {
//Run a function that involves knowing the item I have iterated...
alert( "Handler for "+ item + " called." );
});
}
谢谢,
AJ。
答案 0 :(得分:0)
由于您要分配给全局项目,因此无法正常工作。因为,javascript只有全局和函数本地,说
var item = ids[ i ];
也不起作用。您可以使用jQuery的每个方法迭代您的数组:
$.each( ids, function( index, value ) {
$( value ).click( function() { } );
} );
或者以这种方式将你的项目包装在一个函数中:
for( i=0; i<ids.length; i++ ) {
(function(value) {
$( value ).click(function() { });
})( ids[i] )
}
你也可以这样做
$( ids.join( ',' ) ).click( function(e) {
// No variable "item" available here
// access the target element by $(this) or $(e.target)
} );
答案 1 :(得分:0)
这是一个解决这两个问题所需的最小变化的片段。
问题#1:在#
数组中错过forth
之前的ids
。
问题2:点击处理程序需要使用this
代替item
。
//Choose which ids I want to iterate
ids = ['#first', '#second', '#third', '#forth']
//For all the ids there are
for ( i=0; i<ids.length; i++ ) {
//Select an item
item = ids[i]
//Add a click handler to that item
$( item ).click(function() {
//Run a function that involves knowing the item I have iterated...
alert( "Handler for "+ this.id + " called." );
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="first">First</a><br>
<a href="#" id="second">Second</a><br>
<a href="#" id="third">Third</a><br>
<a href="#" id="forth">Forth</a><br>