开发者

Canceling event bubbling on specific elements - javascript

开发者 https://www.devze.com 2022-12-21 04:50 出处:网络
Basically, I want to make clicking anywhere on a page except in an input field and on one block level element (an by extension all children there in) erase said input field.So I put an onclick event o

Basically, I want to make clicking anywhere on a page except in an input field and on one block level element (an by extension all children there in) erase said input field. So I put an onclick event on the wh开发者_开发问答ole document. To keep the conditions above I put conditions before the clear instructions to only do it if the event did not arise from specific elements.

clearSearch = function (e){
 e ? e : e = window.event;
 e.target ? target = e.target : target = e.srcElement;
 if (target.nodeName != "INPUT" && document.getElementById('ul'))
 document.getElementById('input').value = "";
}

With this method if I want to keep clicking on the ul from causing the action I have to explicitly state it in this if statement. Then I have to do the same for the li elements under the ul. Then any other children I create.

Basically this seems really inefficient and I was wondering if someone could help me out in thinking up a better solution to this mess I have created for myself.


You can remove the complex logic from clearSearch and just have it clear the search box. Then add some new onClick handlers to the elements you don't want to call this method. In those handlers set event.cancelBubble to true to prevent the clearSearch function being called.

From quirksmode:

For a complete cross-browser experience do:

function doSomething(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消