使用循环将事件设置为DOM对象
set events to DOM objects using loop
我有一些DOM输入,我向它们添加了一些事件,输入如下:
$("#hotel2city").keyup(function(){
getDestinations($("#hotel2city"));
});
$("#hotel2name").keyup(function(){
getHotels($("#hotel2city").val(),$("#hotel2name"));
});
的工作,我想做的是不重复上面的代码,但有一个for循环附加的事件。所以我写了一个life:
var setControlls = function(){
for(var i=1; i<=5; i++){
$("#hotel" + i +"city").keyup(function(){
getDestinations($("#hotel"+i+"city"));
});
$("#hotel"+i+"name").keyup(function(){
getHotels($("#hotel"+i+"city").val(),$("#hotel"+i+"name"));
});
}
}();
但这不起作用,知道我做错了什么吗?
使用一个类将事件一次性添加到所有元素中,然后使用元素的ID在侦听器中执行所需的特定功能:
<input type='text' class='keyup-hotel-input' id="hotel2name">
<input type='text' class='keyup-hotel-input' id="hotel2city">
...
<input type='text' class='keyup-hotel-input' id="hotel5name">
<input type='text' class='keyup-hotel-input' id="hotel5city">
$('.keyup-hotel-input').on('keyup',function(e) {
if(this.id.match('city')) {
getDestinations($(this).val());
} else {
getHotels($(this).val());
}
});
最好给它一个class,然后给它一个data-id
之类的,这样它就可以伸缩了:
<div class="hotelCity" data-id="10"></div>
JS:
$(".hotelCity").on("keyup", function(){
getDestinations($(this).data("id"));
});
等等
您的问题是范围,i
将始终是最高的数字。如果你想解决你的问题,使用这个:
var setControlls = function(){
for(var i=1; i<=5; i++){
(function(j){ // Create scope
$("#hotel" + j +"city").keyup(function(){
getDestinations($("#hotel"+j+"city"));
});
$("#hotel"+i+"name").keyup(function(){
getHotels($("#hotel"+j+"city").val(),$("#hotel"+j+"name"));
});
})(i); // Call scope j=i;
}
}();
只需为它们添加一个类,并将元素的id传递给函数,而不是基于id编写多个事件:
<input id="hotel2city" class="hotelcity"/>
<input id="hotel2name" class="hotelname"/>
并在类选择器上写事件:
$(".hotelcity").keyup(function(){
getDestinations(this.id);
});
$(".hotelname").keyup(function(){
getHotels($(this).val(),this);
});
相关文章:
- 将GET请求(HTML字符串)转换为完整的DOM对象
- 在Angular中呈现DOM对象时,如何调用控制器中指定的函数
- 不带dom对象的jquery ajaxComplete()
- 从 DOM 数组中删除 DOM 对象
- Raphael JS:如何从 Dom 对象(Element.node)获取 Raphael 元素
- SVG DOM对象间距/重叠
- DOM对象而不是其他DOM对象
- 如何区分DOM对象和JavaScript对象
- 在提取dom对象后,无法将每个名为tab的元素推送到数组中
- M项目2:是否可以从DOM对象中获取M视图
- Javascript关闭DOM对象事件和事件冒泡
- 如何使用jQuery将重复类添加到DOM对象中
- 当请求DOM对象时,XMLHttpRequest.send()抛出异常
- 从非DOM对象内部调度和处理自定义事件
- dom对象创建javascript和jquery后的事件触发器
- 使用Internet Explorer检索XML DOM对象的URI
- 如何将事件绑定到没有DOM对象的函数
- 使用 Aurelia动态创建一个 dom 对象
- 使用 jQuery 操作 DOM 对象
- 使用多个 css 类将 css 转换属性应用于 DOM 对象时遇到问题