试图用jQuery隐藏()一个元素

时间:2022-12-02 17:41:23

I have code that does this:

我有代码执行此操作:

$('.attachment-medium').each(function(){
$(this).click(function(){
    var gallWidth = $('.gallery').width();
    $('.gall-output').toggle().css('width', gallWidth);
    var url = $(this).attr('src').slice(0,-12) + '.jpg';
    $('.gall-output-img').html('<img class="img-responsive" src="' + url + ' "/>');
    var imgMeta = $(this).parent().next().html();
    $('#gall-output-meta').html(imgMeta);
});
});

This generates a modal overlay and displays an img withing a div with class .gall-output. I've created a small <p class="gall-close">close</p> to hide() the .gall-output but it doesn't seem to be working with this code:

这将生成一个模态叠加并显示一个带有类.gall-output的div的img。我已经创建了一个小的

close 来隐藏().gall-output,但它似乎不能使用这段代码:

$('.gall-close').click(function() {
    $('.gall-output').hide();
});

Is there a way of using this .gall-close to hide or toggle .gall-output?

有没有办法使用这个.gall-close来隐藏或切换.gall-output?

Thanks for your help.

谢谢你的帮助。

1 个解决方案

#1


1  

In case the .gall-close is added later and not in the dom when the page is loaded, you can attach the click-event using event-delegation:

如果稍后添加.gall-close而不是在加载页面时在dom中添加,则可以使用事件委派附加click事件:

$(document).on("click", ".gall-close", function(){
    $('.gall-output').hide();
});

Instead of $(document) any static parent element can work as container element to delegate the event. In case this solves your issue, you can check https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":

而不是$(document)任何静态父元素都可以作为容器元素来委托事件。如果这可以解决您的问题,您可以查看https://api.jquery.com/on/#on-events-selector-data-handler,“直接和委派事件”部分:

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

“事件处理程序仅绑定到当前选定的元素;它们必须存在于代码调用.on()时页面上。”

#1


1  

In case the .gall-close is added later and not in the dom when the page is loaded, you can attach the click-event using event-delegation:

如果稍后添加.gall-close而不是在加载页面时在dom中添加,则可以使用事件委派附加click事件:

$(document).on("click", ".gall-close", function(){
    $('.gall-output').hide();
});

Instead of $(document) any static parent element can work as container element to delegate the event. In case this solves your issue, you can check https://api.jquery.com/on/#on-events-selector-data-handler, section "Direct and delegated events":

而不是$(document)任何静态父元素都可以作为容器元素来委托事件。如果这可以解决您的问题,您可以查看https://api.jquery.com/on/#on-events-selector-data-handler,“直接和委派事件”部分:

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

“事件处理程序仅绑定到当前选定的元素;它们必须存在于代码调用.on()时页面上。”