ホームページ >ウェブフロントエンド >jsチュートリアル >jquery_jquery で特定の要素が繰り返しバインドされる問題の簡単な分析
ある夜、コードを書いているときに突然バグが発生しました。長い間考えた後、どこに問題があるのかわかりませんでした(実際には非常に単純な問題でしたが、私はまだ初心者でした)。だから知りませんでした)。その間の過程は言うに及ばず、紆余曲折を経て、倒れそうになったときにようやくその理由が分かりました。同じ jquery 要素が繰り返しバインドされる可能性があり、ネストされたバインディングが使用されるとエラーが発生しやすくなることがわかりました。たとえば、コード:
New method in jQuery 1.3. Bind an event handler (such as click event) to all current and future matching elements. Custom events can also be bound.
Currently supports click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup.
Blur, focus, mouseenter, mouseleave, change, submit
are not supported yetDifferent from bind(), live() can only bind one event at a time.
This method is very similar to traditional bind. The difference is that using live to bind events will bind events to all current and future elements on the page (using delegation). For example, if you use live to bind click events to all li on the page. Then when a li is added to this page in the future, the click event of this newly added li is still available. There is no need to re-bind events to this newly added element.
.live() is very similar to the popular liveQuery plugin, but has the following major differences:
•.live currently only supports a subset of all events. Please refer to the description above for the supported list.
•.live does not support the "eventless" style callback function provided by liveQuery. .live can only bind event handling functions.
•.live does not have "setup" and "cleanup" processes. Because all events are delegated rather than directly bound to elements.
To remove events bound with live, please use the die method
Usage example:
jquery:
$(“.myDiv”).live(“click”, function(){
alert(“clicked!”);
});
If you use javascript to dynamically create an element with class mydiv, a pop-up will still appear when you click on the element. Why does it happen after using live? This is because jquery uses the event bubbling mechanism to directly bind the event to the document, and then finds the source of the event through event.target. This is different from the jquery.livequery plug-in. jquery.livequery checks every 20 milliseconds and rebinds the event if there is a new one.
Of course there are advantages and disadvantages to using live:
The advantage is: You don’t have to define events repeatedly when updating elements.
The disadvantage is: Binding the event to the document will call it once for every element on the page. Improper use will seriously affect performance. And it does not support blur, focus, mouseenter, mouseleave, change, submit.