隐藏元素后面的逻辑 [英] Logic behind hiding elements

查看:95
本文介绍了隐藏元素后面的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个特定问题的逻辑中有两难的境地。原谅我,如果这是一个相当新手的问题,但我宁愿有一个坚实的bg。



这里有很多例子,在网站上,你点击在一个元素上显示另一个元素。这种情况可能是一个菜单,当您将鼠标悬停在其上(或单击它)显示。后来元素被隐藏在鼠标外,或点击任何其他元素..所以,这是如何实现的?我确定解决方案不是在所有元素上绑定hideElem函数。



regards,

解决方案

  $('#target')bind('click',function(event)
{
var $ element = $('#element');
$ element.show();

$(document).one('click',function()
{
$ element.hide();
});

//如果你不停止事件,它将冒泡到文档
//并触发
//这将在显示后立即隐藏元素
//我们不想要
event.stopPropagation();
}

你必须记住,当开始时,一个Javascript事件会在整个树上上下移动因此,当您想要监听许多元素上的事件时,您可以将事件侦听器绑定到任何父级。



这称为事件委派。


I am having a dilemma in the logic of this particular issue. Forgive me if this is quite newbie question but I'd rather have a solid bg on it.

There are a lot of examples of this all around the web where you click on an element to display another element. such case may be a menu that when you hover your mouse on it (or click on it) its get displayed. Later the element gets hidden either on mouse out, OR CLICKING ON ANY OTHER ELEMENT.. so, how is this achieved? I am sure the solution is not to bind a "hideElem" function on all the elements.

regards,

解决方案

$('#target').bind('click', function(event)
{
    var $element = $('#element');
    $element.show();

    $(document).one('click', function()
    {
       $element.hide();
    });

    // If you don't stop the event, it will bubble up to the document
    // and trigger the click event we just bound. 
    // This will hide the element right now just after showing it, 
    // we don't want that.
    event.stopPropagation();
}

You have to keep in mind that a Javascript event goes up and down the whole tree when begin fired. So you can bind event listeners to any parent when you want to listen for an event on many elements.

This is called event delegation.

这篇关于隐藏元素后面的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆