尝试用jQuery隐藏()一个元素 [英] Trying to hide() an element with jQuery
问题描述
我有这样的代码:
$('。attachment-medium'
$(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-responsivesrc ='+ url +'/>');
var imgMeta = $ ().next()。html();
$('#gall-output-meta')。html(imgMeta);
});
});
这会生成一个模态覆盖,并显示一个带有.gall-output类的div的img。我创建了一个小< p class =gall-close> close< / p>
到 hide $ c>
.gall-output
但它似乎不工作这个代码:
$('。gall-close')。click(function(){
$('。gall-output')。
有没有办法使用.gall关闭隐藏或切换.gall-output? / p>
感谢您的帮助。
$ c> .gall-close 稍后添加,而不是在加载页面时的dom,您可以使用事件委托附加点击事件:
$(document).on(click,.gall-close,function(){
$('。gall-output')。 hide();
});
而不是 $(document)
父元素可以作为容器元素来委派事件。如果这解决了您的问题,您可以检查 https:// api。 jquery.com/on/#on-events-selector-data-handler ,直接和委派事件部分:
事件处理程序仅绑定到当前选定的元素;它们必须在代码调用.on()时页面上存在。
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-close').click(function() {
$('.gall-output').hide();
});
Is there a way of using this .gall-close to hide or toggle .gall-output?
Thanks for your help.
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:
$(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":
"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()."
这篇关于尝试用jQuery隐藏()一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!