简体   繁体   English

关闭div onclick <a>jQuery</a>

[英]Close div onclick <a> jquery

I use this code to display a div onclick: 我使用以下代码显示div onclick:

;(function($) {
    $(function () {
        $('.m-help .m-text').hide();
        $('.m-help')
            .live('click', function () {
                $(this).find('.m-text').show();
            })
            .live('click', function () {
                $(this).find('.m-link-close-button').hide();
            });
    });
    $(document).bind('m-ajax-after', function (e, selectors) {
        $('.m-help .m-text').hide();
    });

})(jQuery);

And with this HTML: 并使用此HTML:

<div class="m-help">
    <div class="m-text" style="width: 40px;">
        <?php echo $_helpHtml ?>
        <a href="#" class="m-link-close-button"><span>x</span></a>
    </div>
    <a href="#" onclick="return false;" class="details m-link"></a>
</div>

This does work onclick to display the div, but I want to use the X mark inside the div to close the div again. 这确实可以在onclick上显示div,但是我想在div中使用X标记再次关闭div。 Closing the div does not work. 关闭div不起作用。

What am I doing wrong and how can I fix this problem? 我在做什么错,如何解决这个问题?

Event delegation 活动委托

$('.m-help').on('click', function (event) {
    var close = $(event.target).closest('.m-link-close-button').length;
    $(this).find('.m-text')[close ? 'hide' : 'show']();
});

http://jsfiddle.net/moogs/9e47j19L/1/ http://jsfiddle.net/moogs/9e47j19L/1/

Use click event on a tag to close the div: 在标签上使用click事件来关闭div:

function($) {
    $(function () {
        $('.m-help .m-text').hide();
        $('.m-help')
            .live('click', function () {
                $(this).find('.m-text').show();
            });

            $(".m-link-close-button").live('click', function () {
               $(this).closest('.m-text').hide();
            });
    });
    $(document).bind('m-ajax-after', function (e, selectors) {
        $('.m-help .m-text').hide();
    });

})(jQuery);

you can get the parent of your close button with parent() so you can do it this way : 您可以使用parent()获取关闭按钮的parent()因此您可以这样操作:

(function($){
   $('.m-help .m-text').hide();
   $('.m-help').live('click', function(ev) {
       $(this).find('.m-text').show();
   });
   $(".m-link-close-button").live('click', function (ev) {
           $(this).parent().hide();
   });
})(jQuery)

try this: HTML 试试这个:HTML

<div class="m-help">
<div class="m-text" style="width: 40px;">
    <?php echo $_helpHtml ?>
    <a href="#" class="m-link-close-button"><span>x</span></a>
</div>
<a href="#" onclick="return false;" class="details m-link">Click</a>
</div>

JS: JS:

$(".m-text").hide();
   $(".m-link").click(function () {
   $(".m-text").show();
});
   $(".m-link-close-button span").click(function () {
   $(".m-text").hide();
});

Working fiddle: http://jsfiddle.net/cncf5Lz9/ 工作提琴: http : //jsfiddle.net/cncf5Lz9/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM