cot*_*tut 0 javascript jquery event-handling javascript-events
目前我所做的是检查页面中是否存在元素.但是我的代码有很多条件,因为那样.当元素不存在时,Jquery事件侦听器不会显示错误.jquery如何处理这个以及我可以使用哪些texniques进行更好的设计?
var el = document.getElementById('el');
var another_el = document.getElementById('another_el');
if(another_el){
el.addEventListener('click', swapper, false);
}
if(el){
el.addEventListener('click', swapper, false);
}
....
...
Run Code Online (Sandbox Code Playgroud)
jquery如何处理...?
jQuery的API是基于集合的,而不是基于元素的.DOM的API是基于元素的.当你$("#foo").on("click", ...)在jQuery的,如果没有元素用id "foo",$()返回一个空集,不null,并呼吁on在该组没有做任何事情,但不会引起任何错误.
由于getElementById返回一个元素或者null,您必须进行检查以防止尝试调用方法null,这会导致错误.
如果您希望在不使用jQuery的情况下获得基于集合的API的好处,您可以编写自己的一组实用程序函数querySelectorAll,如果您愿意,可以使用这些函数为DOM自己提供基于集合的精简包装器.
这是一个非常简单的入门示例:
// The object we use as the prototype of objects returned by `domSet`
var domSetMethods = {
on: function(eventName, handler) {
// Loop through the elements in this set, adding the handler
this.elements.forEach(function(element) {
element.addEventListener(eventName, handler);
});
// To support chaining, return `this`
return this;
}
};
// Get a "DOM set" for the given selector
function domSet(selector) {
// Create the set, usign `domSetMethods` as its prototype
var set = Object.create(domSetMethods);
// Add the elements
set.elements = Array.prototype.slice.call(document.querySelectorAll(selector));
// Return it
return set;
}
domSet("#foo").on("click", function() {
console.log("foo clicked");
});
// Notice that even though there's no id="bar" element, we don't get an error
domSet("#bar").on("click", function() {
console.log("bar clicked");
});Run Code Online (Sandbox Code Playgroud)
<div id="foo">foo element (there is no bar element)</div>Run Code Online (Sandbox Code Playgroud)
您可以添加方法来domSetMethods执行其他操作.为了支持API jQuery提供的链接风格,您this在大多数情况下都会从这些方法返回.
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |