仅在单击DIV元素时如何隐藏

仅在单击DIV元素时如何隐藏

本文介绍了jQuery-仅在单击DIV元素时如何隐藏它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DIV元素,当执行某些操作时会出现.为了简单起见,我编写了一个非常简单的例程来模仿我遇到的问题.但是,我面临的问题是,当您在DIV元素内部(而在textarea外部)单击时,它仍然会隐藏DIV.

I have a DIV element that appears when a certain action is performed. For the sake of simplicity, I wrote a very simple routine that mimics the issue I'm running into. The problem I am facing, however, is that when you click inside the DIV element (and outside the textarea), it will hide the DIV anyway.

这是下面的代码:

<body>
outside div
<br><br>

<a href="#" id="wrap_on">make inside appear</a>
<br><br>

<div id='wrap' style='background:red;display:none;padding:10px;width:155px'>
    <textarea id='inside'>inside div</textarea>
    <div id='inside2'>also inside div -- click me</div>
</div>
</body>

<script>
$(document).ready(function() {
    $('#wrap_on').click(function() {
        $('#wrap').show();
        $('#inside').select().focus();
    });

    $('#inside2').click(function() {
        alert('test');
    });

    // #inside2 does not work but #wrap does hide
    $('#wrap').focusout(function() {
        $('#wrap').hide();
    });
});
</script>

或者您可以在此处进行修改: http://jsfiddle.net/hQjCc/

Or you can tinker with it here: http://jsfiddle.net/hQjCc/

基本上,我希望能够单击文本也在div内-单击我",并弹出警报.但是,.focusout函数阻止了它的工作.另外,如果您在#wrap DIV之外单击,我想将其隐藏.

Basically, I want to be able to click on the text "also inside div -- click me" and have the alert popup. However, the .focusout function is preventing it from working. Also, I want to hide the #wrap DIV if you click outside of it.

推荐答案

$(document).click(function(e) {
    var t = (e.target)
        if(t!= $("#inside").get(0) && t!=$("#inside2").get(0) && t!=$("#wrap_on").get(0) ) {
            $("#wrap").hide();
        }
});

这毕竟应该工作.

http://jsfiddle.net/hQjCc/4/

这篇关于jQuery-仅在单击DIV元素时如何隐藏它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:04