使用JavaScript的onClick关闭一个窗口

4
在我的网站上,有4个窗口(分别标识为target1、target2、target3和target4)。我想在这些窗口上添加一个名为“关闭”的按钮,并使用onClick事件调用正确的函数,具体取决于哪个窗口。
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'
}

这将只关闭触发事件的窗口,但它并不起作用。

有人能帮我吗?

4个回答

2
您可以通过将id作为函数的参数来开始,例如:
function close_window(id) {
    document.getElementById(id).style.display = 'none';
}

这样,您的按钮的onclick应该像这样: "close_window('target1')"

您还可以通过从按钮开始向上遍历DOM来查找要关闭的窗口。为了给您一个例子,我们需要看到实际的HTML。


1

如果我理解正确,您可以简单地使用以下内容:

var windows = $('#target1, #target2, #target3, #target4');
windows.on('click', function() {
  $(this).hide();
});

你应该考虑给按钮添加一个类:

HTML

<div class="windows">
 <button class="close_window">X</button>
</div>

JS

var closeButtons = $('.close_window');
closeButtons.on('click', function() {
  $(this).parent().hide();
});

然后,您就可以实现您想要的目标 :-)
问候

1
不是所有窗口,我只想关闭一个窗口(即我在onclick事件上操作的那个窗口)。 - Simpleacc
我必须将JS添加到HTML的头部,还是可以将其添加到.js文件中? - Simpleacc
随你便。我基本上喜欢将HTML和JS分开。 - Michael Schneider
使用这个函数最容易啦 ^^ - Simpleacc

1
请检查Fiddle。

http://jsfiddle.net/7s49z1zn/

为窗口和关闭按钮添加一个共同的类。
$('.close').click(function(){
    $(this).parents('.window').css('display','none');

});

这应该可以工作


1
我想象中的代码如下:

<div class="window" id="target2">
    <p>TEXT</p>
    <a href="#">Close</a>
</div>

如果你有这样的代码,你可以使用$('.window a').click();来捕获点击事件。
然后获取父元素var parentWindow = $(this).parent(); (为了测试,你可以通过parentWindow.prop('id');获取窗口ID)
最后关闭/隐藏/淡出...parentWindow.fadeOut(); 这里是演示

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接