To make it more clear what I need to do, here is the structure of the search form / HTML page I am working with:
---
|A|
---
--------- --------- ---------
| | | | | |
| B | | B | | B |
| | | | | |
--------- --------- ---------
--------------------------------- ---------
| 开发者_开发技巧 | | C |
| | ---------
| |
| X | ---------
| | | C |
| | ---------
| |
---------------------------------
The boxes A
, B
, C
are buttons which can be clicked by the user.
X
is the content are where the search result will be displayed.
The boxes behave at the moment like this:
- Click on
A
returns to the previous site (= a back button) - Click on
B
andC
apply filter and submit the form (= retrieving the result set of the search) - Click on
X
does nothing - the search result shown here
This works all fine and well.
My new requirement is:
When the user clicks "anything else" then A
, B
, C
or X
then a help message appears in the content area.
As you can imagine, the HTML of the boxes is fairly different and nested, only the boxes of the same type (= same letter) share a CSS class.
E. g. C
looks like this:
My first thought on how to implement this was:
- Attaching an onclick listener to document.body
- Check if the event.target is
A
,B
,C
orX
or contained in any of them - If not, then the user has not clicked a GUI element and the help message is being displayed
This could be made more easy by attaching a common CSS class (gui-element
) to all GUI elements so the document onclick event handler checks only if the event target has this common class.
The drawback is that if any new element e. g. D
is introduced in the HTML it must have this CSS class, too.
Do you think the above approach is good or is there a more "elegant" way of doing this?
EDIT:
A few more details:
- I am using YUI2 as javascript framework
- I know the whole idea of the help message appearing onclick might be ...uh annoying, but I have to do what I am told, sorry
I would go with your first thought, because it would be more maintainable (at least for me)
You can add an onclick handler for the body or some super element, and then stop the event from propogating when you click on of the other elements so it doesn't bubble and you only get the one effect.
function doSomething(e)
{
//handle event
if (!e)
var e = window.event; //if ie do this
e.cancelBubble = true; //ie's stopPropagation method
if (e.stopPropagation) e.stopPropagation(); //w3's stopPropagation
}
source/tutorial on javascript event bubbling
But make sure you do some testing in different browser to make sure it works correctly. :D
精彩评论