使用JavaScript onClick关闭窗口
在我的网站上,我有4个窗口(由target1、target2、target3和target4标识)。在这些窗口上,我想添加一个名为“close”的按钮,并根据哪个窗口使用onClick事件调用正确的函数使用JavaScript onClick关闭窗口,javascript,html,function,window,call,Javascript,Html,Function,Window,Call,在我的网站上,我有4个窗口(由target1、target2、target3和target4标识)。在这些窗口上,我想添加一个名为“close”的按钮,并根据哪个窗口使用onClick事件调用正确的函数 function close_window1(){ document.getElementById('target1').style.display = 'none'; } function close_window2(){ document.getElementById(
function close_window1(){
document.getElementById('target1').style.display = 'none';
}
function close_window2(){
document.getElementById('target2').style.display = 'none';
}
function close_window3(){
document.getElementById('target3').style.display = 'none';
}
function close_window4(){
document.getElementById('target4').style.display = 'none';
}
我相信还有比这更好的方法:
function close_window(){
$(this).parents('div').style.display='none'
}
这将只关闭包含事件的窗口,但它不工作
有人能帮我吗?如果我理解正确,您可以简单地使用这个:
var windows = $('#target1, #target2, #target3, #target4');
windows.on('click', function() {
$(this).hide();
});
你应该考虑给这个按钮上课:
HTML
<div class="windows">
<button class="close_window">X</button>
</div>
然后你就可以实现你想要的目标:-)
关于您可以从将id设置为函数的参数开始,如下所示:
function close_window(id) {
document.getElementById(id).style.display = 'none';
}
这样,按钮的onclick必须看起来像这样:“close_window('target1')”
您还可以通过从按钮开始向上移动DOM来找到要关闭的窗口。为了给你一个例子,我们需要看到实际的HTML。请检查小提琴 为windows和close按钮添加公共类
$('.close').click(function(){
$(this).parents('.window').css('display','none');
}))
这应该是可行的我想象过这样的代码:
<div class="window" id="target2">
<p>TEXT</p>
<a href="#">Close</a>
</div>
正文
如果有这样的代码,可以使用$('.window a')。单击()代码>捕获单击事件
然后获取parentvar parentWindow=$(this.parent()代码>
(对于测试,您可以通过parentWindow.prop('ID');
获取窗口ID)
最后关闭/隐藏/淡出<代码>父窗口。淡出()代码>
这里是不是全部,我只想关闭一个窗口(我只做onlcick事件的窗口)JS我必须将其添加到HTML的头部,或者我可以将其添加到.JS文件中?如您所愿。我基本上喜欢把html和js.Yeha分开,这个函数最简单^^
<div class="window" id="target2">
<p>TEXT</p>
<a href="#">Close</a>
</div>